Beispiel #1
0
 def initDialog(self):
     """Creates buttons for each sequence option and add them to the dialog.
     Maps the clicked signal of those buttons to keep track of what sequence
     gets selected.
     """
     ui_dlg = Ui_AddSeqDialog()
     ui_dlg.setupUi(self.dialog)
     self.signal_mapper = QSignalMapper(self)
     # set up the radio buttons
     for i, name in enumerate(['Abstract', 'Custom'] +
                              sorted(sequences.keys())):
         radio_button = QRadioButton(ui_dlg.group_box)
         radio_button.setObjectName(name + "Button")
         radio_button.setText(name)
         self.buttons.append(radio_button)
         ui_dlg.horizontalLayout.addWidget(radio_button)
         self.signal_mapper.setMapping(radio_button, i)
         radio_button.clicked.connect(self.signal_mapper.map)
         if name in sequences:
             self.sequence_radio_button_id[sequences[name]] = i
     self.signal_mapper.mapped.connect(self.sequenceOptionChangedSlot)
     # disable apply until valid option or custom sequence is chosen
     self.apply_button = ui_dlg.custom_button_box.button(
         QDialogButtonBox.Apply)
     self.apply_button.setEnabled(False)
     # watch sequence textedit box to validate custom sequences
     self.seq_box = ui_dlg.seq_text_edit
     self.seq_box.textChanged.connect(self.validateCustomSequence)
     self.highlighter = DNAHighlighter(self.seq_box)
     # finally, pre-click the first radio button
     self.buttons[0].click()
Beispiel #2
0
    def test(self, step):
        a = 0
        j = 0

        data = get_data(self.topic_id)

        correct = data[step]

        self.question.setText(correct[2])
        self.question.setGeometry(QRect(50, 52, 600, 80))
        font = QtGui.QFont()
        font.setPointSize(13)
        self.question.setFont(font)
        self.question.setWordWrap(True)

        numbers = (self.length - 1 if self.length < 4 else 3)
        failed = random.sample(get_unique_data(self.topic_id, correct[1]), numbers)
        for i in random.sample(failed + [correct], numbers + 1):
            a += 30
            j += 1
            button_name = "radioButton" + str(j)
            button_name = QRadioButton(self.layout)
            if correct[0] != i[0]:
                self.button_group.addButton(button_name, correct[0])
            else:
                self.button_group.addButton(button_name, 0)

            button_name.setGeometry(QRect(50, 100 + a, 255, 17))
            button_name.setObjectName("radioButton" + str(j))
            button_name.setText(i[1])
            button_name.toggled.connect(self.get_answer)
            button_name.show()

        self.input_first.setText('Вопрос № ' + str(self.step + 1) + ' из ' + str(self.length))
Beispiel #3
0
    def initUi(self):

        layout = QGridLayout()

        radio_celsius = QRadioButton('Temperature in Celsius scale')
        radio_celsius.setObjectName('c')
        radio_celsius.setChecked(True)

        radio_fahrenheit = QRadioButton('Temperature in Fahrenheit scale')
        radio_fahrenheit.setObjectName('f')

        line_temp = QLineEdit()
        line_temp.setText('0')

        label_temp = QLabel()

        radio_celsius.toggled.connect(lambda: self.on_toggled_changed(
            radio_celsius, line_temp, label_temp))

        radio_fahrenheit.toggled.connect(lambda: self.on_toggled_changed(
            radio_fahrenheit, line_temp, label_temp))

        layout.addWidget(radio_celsius, 0, 0)
        layout.addWidget(radio_fahrenheit, 1, 0)
        layout.addWidget(line_temp, 2, 0)
        layout.addWidget(label_temp, 3, 0)

        self.setLayout(layout)
Beispiel #4
0
    def get_childs(self, sender):
        """ Generate sub dirs relevant to main menu element """

        self.clear_child_table()
        self.current_parent = sender
        # Create Childs
        self.refresh_element = QToolButton()
        self.refresh_element.setObjectName('refresh')
        self.refresh_element.setIcon(QIcon(':/refresh'))
        self.refresh_element.setIconSize(QSize(22, 22))
        self.refresh_element.setCursor(Qt.PointingHandCursor)
        self.refresh_element.clicked.connect(lambda: self.get_keys(True, refresh=self.refresh_element.statusTip()))
        self.refresh_element.setEnabled(False)
        self.second_layout_keys_childs.addWidget(self.refresh_element)
        self.second_layout_keys_childs.addSpacing(5)
        sql = "SELECT DISTINCT child " \
              "FROM passwords " \
              "WHERE parent=? " \
              "ORDER BY child ASC"
        query = self.cursor.execute(sql, (sender,))
        for item in query.fetchall():
            child_element = QRadioButton()
            child_element.setObjectName("child-element")
            child_element.setText(item[0])
            child_element.setMinimumHeight(22)
            child_element.setCursor(Qt.PointingHandCursor)
            child_element.clicked.connect(self.get_keys)
            self.second_layout_keys_childs.addWidget(child_element)
            self.second_layout_keys_childs.addSpacing(5)
Beispiel #5
0
 def initDialog(self):
     """Creates buttons for each sequence option and add them to the dialog.
     Maps the clicked signal of those buttons to keep track of what sequence
     gets selected.
     """
     ui_dlg = Ui_AddSeqDialog()
     ui_dlg.setupUi(self.dialog)
     self.signal_mapper = QSignalMapper(self)
     # set up the radio buttons
     for i, name in enumerate(['Abstract', 'Custom'] + sorted(sequences.keys())):
         radio_button = QRadioButton(ui_dlg.group_box)
         radio_button.setObjectName(name + "Button")
         radio_button.setText(name)
         self.buttons.append(radio_button)
         ui_dlg.horizontalLayout.addWidget(radio_button)
         self.signal_mapper.setMapping(radio_button, i)
         radio_button.clicked.connect(self.signal_mapper.map)
         if name in sequences:
             self.sequence_radio_button_id[sequences[name]] = i
     self.signal_mapper.mapped.connect(self.sequenceOptionChangedSlot)
     # disable apply until valid option or custom sequence is chosen
     self.apply_button = ui_dlg.custom_button_box.button(QDialogButtonBox.Apply)
     self.apply_button.setEnabled(False)
     # watch sequence textedit box to validate custom sequences
     self.seq_box = ui_dlg.seq_text_edit
     self.seq_box.textChanged.connect(self.validateCustomSequence)
     self.highlighter = DNAHighlighter(self.seq_box)
     # finally, pre-click the first radio button
     self.buttons[0].click()
Beispiel #6
0
def radio_filler(group_caption, labels, buttons_per_row=None, tool_tips=None):
    """ create a QGroupBox filled with a QGridLayout of QRadioButtons 
        that are part of a QButtonGroup
        
        group_caption: 
        
        labels:    list of strings that contain text for QRadioButtons
                   order of this list is important as the index is
                   used for QButtonGroup.Id
                   
        buttons_per_row: optional argument. number of QRadioButtons in
                         each row of the output QGridLayout.
                         
                         If None, all QRadioButtons
                         will be placed on one row. 
                         
        tool_tips: list of toolTip strings that will be added to each
                   QRadioButton.
                   
                   If None, no toolTips are added
    """

    group_box = QGroupBox(group_caption)
    grid = QGridLayout()
    bname = re.split("[\'\/ ,.]+", group_caption)
    bname = ' '.join(bname).title().replace(' ', '')
    bname = 'bgrp' + bname
    button_group = QButtonGroup(group_box)
    button_group.setObjectName(bname)
    # ~ button_group = QButtonGroup(group_box)

    for idx, label in enumerate(labels):
        radio_button = QRadioButton(label)
        # re.split seems to be the only way to quickly split on multiple
        # delimiters
        oname = re.split("[\'\/ ,.\n\-]+", label)
        oname = ' '.join(oname).title().replace(' ', '')
        oname = 'opt' + oname

        radio_button.setObjectName(oname)
        if tool_tips is not None:
            if len(tool_tips) == len(labels):
                radio_button.setToolTip(tool_tips[idx])

        if buttons_per_row is None:
            # all QRadioButtons go in row 0
            row = 0
            col = idx
        else:
            row = int(idx / buttons_per_row)
            col = idx % buttons_per_row
        button_group.addButton(radio_button, idx)  # set Id to idx

        grid.addWidget(radio_button, row, col)

    group_box.setLayout(grid)

    return (group_box, button_group)
Beispiel #7
0
    def show_available_colormaps(self):
        height = 50

        selected = colormaps.read_selected_colormap_name_from_settings()
        for colormap_name in sorted(colormaps.maps.keys()):
            image = Spectrogram.create_colormap_image(colormap_name, height=height)
            rb = QRadioButton(colormap_name)
            rb.setObjectName(colormap_name)
            rb.setChecked(colormap_name == selected)
            rb.setIcon(QIcon(QPixmap.fromImage(image)))
            rb.setIconSize(QSize(256, height))
            self.ui.scrollAreaWidgetSpectrogramColormapContents.layout().addWidget(rb)
Beispiel #8
0
    def createRadio(self, layout_selected, selected):
        from PyQt5.QtWidgets import QRadioButton, QSizePolicy
        from PyQt5.QtGui import QFont

        radioButton = QRadioButton()
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        radioButton.setSizePolicy(sizePolicy)
        radioButton.setObjectName("checkBox")
        radioButton.setChecked(selected)
        radioButton.clicked.connect(lambda: self.modify_value(layout_selected))
        return radioButton
Beispiel #9
0
class RadiobuttonItemsView(QDialog):
    def __init__(self, dbs, selected_db):
        super().__init__()
        self.layout = QGridLayout()
        self.selected_db = selected_db
        self.dbs = dbs

        btn_ok = QPushButton('OK', self)
        btn_ok.clicked.connect(self.ok_pressed)
        btn_cancel = QPushButton('Cancel', self)
        btn_cancel.clicked.connect(self.cancel_pressed)

        scroll = QScrollArea(self)
        scroll.setWidgetResizable(True)
        self.content = QWidget()
        scroll.setWidget(self.content)

        rb_vbox = QVBoxLayout(self.content)
        rb_vbox.addStretch(1)
        self.button_group = QButtonGroup()

        # btn_vbox = QVBoxLayout()
        # btn_vbox.addStretch(1)
        # btn_vbox.addWidget(btn_ok)
        # btn_vbox.addWidget(btn_cancel)

        for db in self.dbs:
            self.button_name = QRadioButton(f"{db}")
            self.button_name.setObjectName(f"radiobtn_{db}")
            rb_vbox.addWidget(self.button_name)
            self.button_group.addButton(self.button_name)

        self.layout.addWidget(scroll, 0, 0)
        self.layout.addWidget(btn_ok, 0, 1)
        self.layout.addWidget(btn_cancel, 0, 2)
        self.setStyleSheet("QScrollArea{min-width:300 px; min-height: 400px}")

        self.setLayout(self.layout)
        self.setModal(True)
        self.show()

    def ok_pressed(self):
        self.selected_db = ''
        for x in range(len(self.button_group.buttons())):
            if self.button_group.buttons()[x].isChecked():
                self.selected_db = self.button_group.buttons()[x].text()
        self.close()

    def cancel_pressed(self):
        self.close()
Beispiel #10
0
class Submodule_Widget(QWidget):            # Module Variant widget with a Name, RadioButton and an Image
    def __init__(self,Iterative,parent):
        super().__init__()
        Module_Name,Image_Path,Object_Name=Iterative
        layout=QVBoxLayout()
        self.setLayout(layout)
        label=QLabel(Module_Name)
        layout.addWidget(label)
        label.setObjectName('module_name_label')
        self.rdbtn=QRadioButton()
        self.rdbtn.setObjectName(Object_Name)
        self.rdbtn.setIcon(QIcon(Image_Path))

        self.rdbtn.setIconSize(QSize(scale*300, scale*300))

        layout.addWidget(self.rdbtn)
        self.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed))
    def _show_menu(self):
        """
        Update menu on showEvent.
        """

        for i, item in enumerate(self.visible_items):
            b = QRadioButton(self._get_button_name(item))
            b.setChecked(i == 0)
            b.clicked.connect(functools.partial(self.templates_layout.setCurrentIndex, i))
            b.setObjectName("menu_button")
            self.menu_layout.addWidget(b)

        if not self.visible_items:
            self.menu_layout.addStretch()
            l = QLabel("Чтобы создать отчет\nначните заполнять данные")
            l.setAlignment(Qt.AlignCenter)
            self.menu_layout.addWidget(l)

        self.menu_layout.addStretch()
Beispiel #12
0
    def modelButtonGroup(self):
        """
        A widget of radio buttons that will determine which QStackedWidget is
        displayed.
        """

        # It seems that in order for the buttonClicked signal to work,
        # self.ButtonGroup and not ButtonGroup is necessary. Does not work
        # with out 'self.' prefix!!!

        modelsWidget = QWidget()
        modelsWidget.setObjectName('modelswidget')
        modelsLayout = QVBoxLayout()
        modelsLayout.setObjectName('modelslayout')
        self.ButtonGroup = QButtonGroup()

        selectModelLabel = QLabel('Select Model:')
        selectModelLabel.setAlignment(Qt.AlignCenter)
        selectModelLabel.setStyleSheet('color: white')

        twosingletbutton = QRadioButton('Two uncoupled spin-1/2 nuclei')
        twosingletbutton.setObjectName('twosingletbutton')
        twosingletbutton.setStyleSheet('color: white')
        twosingletbutton.setChecked(True)
        self.ButtonGroup.addButton(twosingletbutton, 0)

        abbutton = QRadioButton('Two coupled spin-1/2 nuclei\n ("AB quartet)')
        abbutton.setObjectName('abbutton')
        abbutton.setStyleSheet('color: white')
        self.ButtonGroup.addButton(abbutton, 1)

        self.ButtonGroup.buttonClicked[int].connect(self.switchView)

        modelsLayout.addStretch()
        modelsLayout.addWidget(selectModelLabel)
        modelsLayout.addWidget(twosingletbutton)
        modelsLayout.addWidget(abbutton)
        modelsLayout.addStretch()
        modelsWidget.setLayout(modelsLayout)
        modelsWidget.setStyleSheet("background-color: rgb(60, 63, 65);")

        return modelsWidget
Beispiel #13
0
    def _show_menu(self):
        """
        Update menu on showEvent.
        """

        for i, item in enumerate(self.visible_items):
            b = QRadioButton(self._get_button_name(item))
            b.setChecked(i == 0)
            b.clicked.connect(
                functools.partial(self.templates_layout.setCurrentIndex, i))
            b.setObjectName('menu_button')
            self.menu_layout.addWidget(b)

        if not self.visible_items:
            self.menu_layout.addStretch()
            l = QLabel('Чтобы создать отчет\nначните заполнять данные')
            l.setAlignment(Qt.AlignCenter)
            self.menu_layout.addWidget(l)

        self.menu_layout.addStretch()
Beispiel #14
0
 def generate_child_list(self):
     self.sender().blockSignals(True)
     for pos in reversed(range(self.cc.count())):
         curr_item = self.cc.takeAt(pos).widget()
         if curr_item is not None:
             curr_item.deleteLater()
     sql = "SELECT DISTINCT child " \
           "FROM passwords " \
           "WHERE parent=? " \
           "ORDER BY child ASC"
     query = self.cursor.execute(sql, (self.combo.currentText(), ))
     for item in query.fetchall():
         r_elem = QRadioButton()
         r_elem.setObjectName("child-element")
         r_elem.setText(item[0])
         r_elem.setFixedHeight(20)
         r_elem.setCursor(Qt.PointingHandCursor)
         r_elem.clicked.connect(self.child_text_replace)
         self.cc.addWidget(r_elem)
     self.sender().blockSignals(False)
    def __init__(self, root, controller, parent=None):
        super(self.__class__, self).__init__(parent)

        self.setupUi(self)
        add_widget(root, self, 'IDGAMES_DETAIL')

        self.controller = controller

        self.mirror_button_group = QButtonGroup()
        self.button_layout = self.findChild(QVBoxLayout, 'idgames_detail_download_layout')
        radio_button_labels = ['Germany','Idaho','Greece','Greece (HTTP)','Texas','Germany (TLS)','New York','Virginia']
        for i, label in enumerate(radio_button_labels):
            radio_button = QRadioButton(label)
            radio_button.setObjectName(label.upper())
            radio_button.setChecked(i == 0)
            self.button_layout.insertWidget(1 + i, radio_button)
            self.mirror_button_group.addButton(radio_button)

        data_labels = ['title', 'filename', 'size', 'date', 'author', 'description', 'credits', 'base', 'buildtime', 'editors', 'bugs','rating']
        self.idgames_response_widget = IdgamesResponseWidget(self, data_labels, 'idgames_detail', self.download, data_labels)
Beispiel #16
0
 def initFullBox(self):
     fullbox = QHBoxLayout()
     fullbox_container = QVBoxLayout()
     fullboxRating = QHBoxLayout()
     fullbox_container.addLayout(fullboxRating)
     fullbox_container.setContentsMargins(200, 0, 200, 0)
     fullbox.addLayout(fullbox_container)
     button_group = QButtonGroup(fullbox)
     for i in range(5):
         ratingBtn = QRadioButton()
         ratingBtn.toggled.connect(
             partial(self.setPieceRating, self.model.curr_piece_idx, i + 1))
         if self.model.curr_piece.user_score == i + 1:
             ratingBtn.setChecked(True)
         ratingBtn.setObjectName('rating-btn')
         ratingBtn.setStyleSheet(f"background-color: {self.btn_colors[i]}; "
                                 f"border: 10px solid {self.btn_colors[i]};"
                                 f"border-radius: 14px; ")
         button_group.addButton(ratingBtn)
         fullboxRating.addWidget(ratingBtn)
     return fullbox
Beispiel #17
0
    def __generateSurroundingWidget__(self):
        surroundGB = QGroupBox()
        surroundGB.setFlat(True)
        surroundLayout = QVBoxLayout()
        surroundLayout.setContentsMargins(0, 0, 0, 0)

        noneRB = QRadioButton(self.tr("&None"))
        noneRB.setObjectName("None")
        noneRB.setChecked(True)
        surroundLayout.addWidget(noneRB)

        adjacentRB = QRadioButton(self.tr("&Adjacent streets"))
        adjacentRB.setObjectName("Adjacent")
        surroundLayout.addWidget(adjacentRB)

        aroundRB = QRadioButton(self.tr("&Streets around"))
        aroundRB.setObjectName("Around")
        surroundLayout.addWidget(aroundRB)

        aroundRadiusEdit = QLineEdit("")
        aroundRadiusEdit.hide()
        aroundRadiusEdit.setPlaceholderText("Radius in meters")
        aroundRadiusEdit.setValidator(QIntValidator(0, 10000000, surroundGB))
        aroundRB.toggled.connect(lambda b: aroundRadiusEdit.show() if b else aroundRadiusEdit.hide())
        surroundLayout.addWidget(aroundRadiusEdit)

        surroundGB.setLayout(surroundLayout)

        return surroundGB, aroundRadiusEdit
Beispiel #18
0
    def initDialog(self):
        """
        1. Create buttons according to available scaffold sequences and
        add them to the dialog.
        2. Map the clicked signal of those buttons to keep track of what
        sequence gets selected.
        3. Watch the tab_widget change signal to determine whether a
        standard or custom sequence should be applied.
        """
        ui_dlg = Ui_AddSeqDialog()
        ui_dlg.setupUi(self.dialog)
        self.signal_mapper = QSignalMapper(self)
        # set up the radio buttons
        for i, name in enumerate(sorted(sequences.keys())):
            radio_button = QRadioButton(ui_dlg.group_box)
            radio_button.setObjectName(name + "Button")
            radio_button.setText(name)
            self.buttons.append(radio_button)
            ui_dlg.verticalLayout.addWidget(radio_button)
            self.signal_mapper.setMapping(radio_button, i)
            radio_button.clicked.connect(self.signal_mapper.map)
        self.signal_mapper.mapped.connect(self.standardSequenceChangedSlot)
        ui_dlg.tab_widget.currentChanged.connect(self.tabWidgetChangedSlot)
        # disable apply until valid option or custom sequence is chosen
        self.apply_button = ui_dlg.custom_button_box.button(
            QDialogButtonBox.Apply)
        self.apply_button.setEnabled(False)
        # watch sequence textedit box to validate custom sequences
        self.seq_box = ui_dlg.seq_text_edit
        self.seq_box.textChanged.connect(self.validateCustomSequence)
        self.highlighter = DNAHighlighter(self.seq_box)
        # finally, pre-click the M13mp18 radio button
        self.buttons[0].click()
        buttons = self.buttons

        self.dialog.setFocusProxy(ui_dlg.group_box)
        self.dialog.setFocusPolicy(Qt.TabFocus)
        ui_dlg.group_box.setFocusPolicy(Qt.TabFocus)
        for i in range(len(buttons) - 1):
            ui_dlg.group_box.setTabOrder(buttons[i], buttons[i + 1])
Beispiel #19
0
    def initDialog(self):
        """
        1. Create buttons according to available scaffold sequences and
        add them to the dialog.
        2. Map the clicked signal of those buttons to keep track of what
        sequence gets selected.
        3. Watch the tabWidget change signal to determine whether a
        standard or custom sequence should be applied.
        """
        uiDlg = Ui_AddSeqDialog()
        uiDlg.setupUi(self.dialog)
        self.signalMapper = QSignalMapper(self)
        # set up the radio buttons
        for i, name in enumerate(sorted(sequences.keys())):
            radioButton = QRadioButton(uiDlg.groupBox)
            radioButton.setObjectName(name + "Button")
            radioButton.setText(name)
            self.buttons.append(radioButton)
            uiDlg.verticalLayout.addWidget(radioButton)
            self.signalMapper.setMapping(radioButton, i)
            radioButton.clicked.connect(self.signalMapper.map)
        self.signalMapper.mapped.connect(self.standardSequenceChangedSlot)
        uiDlg.tabWidget.currentChanged.connect(self.tabWidgetChangedSlot)
        # disable apply until valid option or custom sequence is chosen
        self.applyButton = uiDlg.customButtonBox.button(QDialogButtonBox.Apply)
        self.applyButton.setEnabled(False)
        # watch sequence textedit box to validate custom sequences
        self.seqBox = uiDlg.seqTextEdit
        self.seqBox.textChanged.connect(self.validateCustomSequence)
        self.highlighter = DNAHighlighter(self.seqBox)
        # finally, pre-click the M13mp18 radio button
        self.buttons[0].click()
        buttons = self.buttons

        self.dialog.setFocusProxy(uiDlg.groupBox)
        self.dialog.setFocusPolicy(Qt.TabFocus)
        uiDlg.groupBox.setFocusPolicy(Qt.TabFocus)
        for i in range(len(buttons)-1):
            uiDlg.groupBox.setTabOrder(buttons[i], buttons[i+1])
Beispiel #20
0
 def Excel_Loader(self):
     # ------------title----------------------------------
     self.csv_title = QLabel()
     self.csv_title.setObjectName("title_label")
     self.csv_title.setText('路径')
     self.grid.addWidget(self.csv_title, 2,1,1,22, Qt.AlignLeft | Qt.AlignVCenter)
     # ------------lable----------------------------------
     self.csv_lable = QLabel()
     self.csv_lable.setObjectName("normal_label")
     self.csv_lable.setText('请点击右侧按钮选择市场预算表......')
     self.grid.addWidget(self.csv_lable, 5,2,2,19, Qt.AlignLeft | Qt.AlignVCenter)
     # ------------load_btn----------------------------------
     self.csv_btn = QPushButton('...')
     self.csv_btn.setObjectName('load_btn_CSV')
     self.csv_btn.clicked.connect(self.msg)
     self.grid.addWidget(self.csv_btn, 5,21,2,2, Qt.AlignRight | Qt.AlignVCenter)
     # ------------title----------------------------------
     self.csv_title = QLabel()
     self.csv_title.setObjectName("title_label")
     self.csv_title.setText('表名')
     self.grid.addWidget(self.csv_title, 9, 1, 1, 22, Qt.AlignLeft | Qt.AlignVCenter)
     #-----------------rb---------------------------------
     self.bg1 = QButtonGroup()
     for index,item in enumerate(ROUTER.keys()):
         rb = QRadioButton(item)
         rb.setObjectName('rb_btn')
         if index < 4:
             self.grid.addWidget(rb, 11, 3+index*5, 2, 5, Qt.AlignLeft | Qt.AlignVCenter)
         elif index < 8:
             self.grid.addWidget(rb, 14, index*5-17, 2, 5, Qt.AlignLeft | Qt.AlignVCenter)
         else:
             self.grid.addWidget(rb, 17, index * 5 - 37, 2, 5, Qt.AlignLeft | Qt.AlignVCenter)
         self.bg1.addButton(rb, index)
      # -------------submit_btn-------------------------------
     self.sub_btn = QPushButton('点          击          上          传')
     self.sub_btn.setObjectName('submit_btn')
     self.sub_btn.clicked.connect(self.submit)
     self.grid.addWidget(self.sub_btn, 21, 2, 2, 18, Qt.AlignRight | Qt.AlignVCenter)
Beispiel #21
0
    def initUI(self):
        """Initializes the widgets elements (buttons, and tools in general)"""

        self.setFixedSize(250, 300)
        self.setStyleSheet('color: white; font-size: 14px')
        layout = QVBoxLayout()
        name_label = QLabel('Frame name')
        name_edit = QLineEdit()
        name_edit.setPlaceholderText('Frame name')
        name_edit.setMaximumWidth(200)
        data_label = QLabel('Data type')
        self.button_group = QButtonGroup()
        self.button_group.setExclusive(True)
        rgb_image_data = QRadioButton('RGB Image')
        rgb_image_data.setObjectName('rgbimage')
        depth_image_data = QRadioButton('Depth Image')
        depth_image_data.setObjectName('depthimage')
        laser_data = QRadioButton('Laser Data')
        laser_data.setObjectName('laser')
        pose_data = QRadioButton('Pose3D Data')
        pose_data.setObjectName('pose')
        rgb_image_data.setChecked(True)
        depth_image_data.setEnabled(False)
        self.button_group.addButton(rgb_image_data)
        self.button_group.addButton(laser_data)
        self.button_group.addButton(pose_data)
        self.button_group.addButton(depth_image_data)
        self.aspect_ratio = QCheckBox('Keep aspect ratio')
        self.aspect_ratio.setChecked(True)
        confirm_button = QPushButton('Confirm')
        confirm_button.setMaximumWidth(200)

        self.button_group.buttonClicked.connect(self.button_handle)
        confirm_button.pressed.connect(self.confirm_configuration)
        name_edit.textChanged[str].connect(self.change_name)

        layout.addWidget(name_label, alignment=Qt.AlignCenter)
        layout.addWidget(name_edit)
        layout.addWidget(data_label, alignment=Qt.AlignCenter)
        layout.addWidget(rgb_image_data)
        layout.addWidget(depth_image_data)
        layout.addWidget(laser_data)
        layout.addWidget(pose_data)
        layout.addWidget(HLine())
        layout.addWidget(self.aspect_ratio, alignment=Qt.AlignLeft)
        layout.addWidget(confirm_button)

        self.setLayout(layout)
Beispiel #22
0
class Window(QWidget):
    def __init__(self):

        super().__init__()
        self.initUi()

        self.show()

    def initUi(self):

        self.button_blue = QRadioButton('Change background to color blue')
        self.button_blue.setObjectName('blue')
        self.button_green = QRadioButton('Change background to color green')
        self.button_green.setObjectName('green')
        self.button_red = QRadioButton('Change background to color blue')
        self.button_red.setObjectName('red')

        self.label = QLabel('Colored label')

        self.layout = QGridLayout()

        self.layout.addWidget(self.button_blue, 0, 0)
        self.layout.addWidget(self.button_green, 1, 0)
        self.layout.addWidget(self.button_red, 2, 0)
        self.layout.addWidget(self.label, 0, 1, 3, 1)

        self.button_blue.clicked.connect(
            lambda: self.on_button_clicked(self.button_blue))
        self.button_green.clicked.connect(
            lambda: self.on_button_clicked(self.button_green))
        self.button_red.clicked.connect(
            lambda: self.on_button_clicked(self.button_red))

        self.setLayout(self.layout)

    def on_button_clicked(self, sender):

        if sender.objectName() == 'blue':
            self.label.setStyleSheet('background-color:blue;')
        elif sender.objectName() == 'green':
            self.label.setStyleSheet('background-color:green;')
        else:
            self.label.setStyleSheet('background-color:red;')
Beispiel #23
0
class PreviewWidgetStyle(QGroupBox):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setTitle(self.tr("Preview"))
        self.setMaximumHeight(220)
        self.setObjectName("groupBox")

        self.verticalLayout = QVBoxLayout(self)
        self.verticalLayout.setObjectName("verticalLayout")

        self.tabWidget = QTabWidget(self)
        self.tabWidget.setObjectName("tabWidgetPreview")

        self.tab = QWidget()
        self.tab.setObjectName("tab")

        self.horizontalLayout = QHBoxLayout(self.tab)
        self.horizontalLayout.setObjectName("horizontalLayout")

        self.groupBox = QGroupBox(self.tab)
        self.groupBox.setTitle(self.tr("Group Box"))
        self.groupBox.setObjectName("groupBox")

        self.verticalLayout_2 = QVBoxLayout(self.groupBox)
        self.verticalLayout_2.setObjectName("verticalLayout_2")

        self.radioButton = QRadioButton(self.groupBox)
        self.radioButton.setText(self.tr("Radio Button"))
        self.radioButton.setChecked(True)
        self.radioButton.setObjectName("radioButton")
        self.verticalLayout_2.addWidget(self.radioButton)

        self.radioButton_2 = QRadioButton(self.groupBox)
        self.radioButton_2.setText(self.tr("Radio Button"))
        self.radioButton_2.setObjectName("radioButton_2")
        self.verticalLayout_2.addWidget(self.radioButton_2)

        self.line = QFrame(self.groupBox)
        self.line.setFrameShape(QFrame.HLine)
        self.line.setFrameShadow(QFrame.Sunken)
        self.line.setObjectName("line")
        self.verticalLayout_2.addWidget(self.line)

        self.checkBox = QCheckBox(self.groupBox)
        self.checkBox.setText(self.tr("Check Box"))
        self.checkBox.setChecked(True)
        self.checkBox.setObjectName("checkBox")
        self.verticalLayout_2.addWidget(self.checkBox)

        self.horizontalLayout.addWidget(self.groupBox)

        self.verticalLayout_3 = QVBoxLayout()
        self.verticalLayout_3.setObjectName("verticalLayout_3")

        self.progressBar = QProgressBar(self.tab)
        self.progressBar.setProperty("value", 75)
        self.progressBar.setObjectName("progressBar")
        self.verticalLayout_3.addWidget(self.progressBar)

        self.horizontalSlider = QSlider(self.tab)
        self.horizontalSlider.setProperty("value", 45)
        self.horizontalSlider.setSliderPosition(45)
        self.horizontalSlider.setOrientation(Qt.Horizontal)
        self.horizontalSlider.setObjectName("horizontalSlider")
        self.verticalLayout_3.addWidget(self.horizontalSlider)

        self.horizontalLayout_2 = QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")

        self.spinBox = QSpinBox(self.tab)
        self.spinBox.setObjectName("spinBox")
        self.horizontalLayout_2.addWidget(self.spinBox)

        self.pushButton = QPushButton(self.tab)
        self.pushButton.setText(self.tr("Button"))
        self.pushButton.setObjectName("pushButton")
        self.horizontalLayout_2.addWidget(self.pushButton)

        self.verticalLayout_3.addLayout(self.horizontalLayout_2)

        self.comboBox = QComboBox(self.tab)
        self.comboBox.setObjectName("comboBox")
        self.comboBox.addItem(self.tr("Combo Box"))
        self.verticalLayout_3.addWidget(self.comboBox)

        self.horizontalLayout.addLayout(self.verticalLayout_3)

        self.verticalScrollBar = QScrollBar(self.tab)
        self.verticalScrollBar.setPageStep(50)
        self.verticalScrollBar.setOrientation(Qt.Vertical)
        self.verticalScrollBar.setObjectName("verticalScrollBar")
        self.horizontalLayout.addWidget(self.verticalScrollBar)
        self.tabWidget.addTab(self.tab, self.tr("Tab 1"))

        self.tab_2 = QWidget()
        self.tab_2.setObjectName("tab_2")
        self.tabWidget.addTab(self.tab_2, self.tr("Tab 2"))

        self.verticalLayout.addWidget(self.tabWidget)

        self.pushButton.installEventFilter(self)
        self.pushButton.setFocusPolicy(Qt.NoFocus)
        self.radioButton.installEventFilter(self)
        self.radioButton.setFocusPolicy(Qt.NoFocus)
        self.radioButton_2.installEventFilter(self)
        self.radioButton_2.setFocusPolicy(Qt.NoFocus)
        self.checkBox.installEventFilter(self)
        self.checkBox.setFocusPolicy(Qt.NoFocus)
        self.comboBox.installEventFilter(self)
        self.comboBox.setFocusPolicy(Qt.NoFocus)
        self.spinBox.installEventFilter(self)
        self.spinBox.setFocusPolicy(Qt.NoFocus)
        self.horizontalSlider.installEventFilter(self)
        self.horizontalSlider.setFocusPolicy(Qt.NoFocus)
        self.verticalScrollBar.installEventFilter(self)
        self.verticalScrollBar.setFocusPolicy(Qt.NoFocus)
        self.tab.installEventFilter(self)
        self.tab.setFocusPolicy(Qt.NoFocus)
        self.tab_2.installEventFilter(self)
        self.tab_2.setFocusPolicy(Qt.NoFocus)
        self.tabWidget.installEventFilter(self)
        self.tabWidget.setFocusPolicy(Qt.NoFocus)

        self.tabWidget.currentChanged.connect(self.noClick)

    def noClick(self, x):
        self.tabWidget.setCurrentIndex(0)

    def eventFilter(self, obj, event):
        if self.pushButton:
            if event.type() == QEvent.MouseButtonRelease:
                return True
            elif event.type() == QEvent.MouseButtonPress:
                return True
            elif event.type() == QEvent.MouseButtonDblClick:
                return True
            else:
                return False
        else:
            super().eventFilter(obj, event)
Beispiel #24
0
class WritingPadWidget(QWidget):
    def __init__(self):
        super(WritingPadWidget, self).__init__()

        self.init()
        self.setup_ui()
        self.set_form_layout()

    def init(self):
        self.penColor = Qt.black
        self.penSize = 2

    def setup_ui(self):
        # 结果框
        self.resultFrame = QFrame(self)
        self.resultFrame.setObjectName('resultFrame')
        self.textEdit = QTextEdit()
        self.textEdit.setObjectName('textEdit')

        self.frame1 = QFrame()
        self.frame1.setObjectName('frame1')

        # 手写台
        self.writingPad = WritingPad(self.penColor, self.penSize)
        self.writingPad.setObjectName('writingPad')
        self.writingPad.setFrameShape(QFrame.StyledPanel)

        self.frame2 = QFrame()
        self.frame2.setObjectName('frame2')

        # 控制面板
        self.controlPanel = QFrame(self)
        self.controlPanel.setObjectName('controlPanel')

        # 笔触样式预览
        self.viewBox = QGroupBox()
        self.viewBox.setObjectName('viewBox')

        self.viewLabel = QLabel()
        self.viewLabel.setObjectName('viewLabel')

        # 加载控制面板控件
        self.control_panel()
        # 加载控制面板布局
        self.set_controlpanel_layout()

    def control_panel(self):
        """
        控制面板控件
        :return:
        """
        self.buttonWidget = QWidget()

        self.radioButton1 = QRadioButton('经典笔触颜色样式')
        self.radioButton1.setObjectName('radioButton')
        self.radioButton2 = QRadioButton('自定义笔触颜色样式 ')
        self.radioButton2.setObjectName('radioButton')

        # 按钮控件
        self.resumeBtn = QPushButton(self.buttonWidget)
        self.resumeBtn.setObjectName('paintBtn')
        self.resumeBtn.setIconSize(QSize(50, 50))
        self.resumeBtn.setIcon(
            QIcon(
                './image/mainWindowIcon/RightForm2Image/writingPad/resume.png')
        )
        self.resumeBtn.clicked.connect(lambda: self.resume())

        self.cancelBtn = QPushButton(self.buttonWidget)
        self.cancelBtn.setObjectName('paintBtn')
        self.cancelBtn.setIconSize(QSize(50, 50))
        self.cancelBtn.setIcon(
            QIcon(
                './image/mainWindowIcon/RightForm2Image/writingPad/cancel.png')
        )
        self.cancelBtn.clicked.connect(lambda: self.cancel())

        self.clearBtn = QPushButton(self.buttonWidget)
        self.clearBtn.setObjectName('paintBtn')
        self.clearBtn.setIconSize(QSize(50, 50))
        self.clearBtn.setIcon(
            QIcon(
                './image/mainWindowIcon/RightForm2Image/writingPad/clear.jpg'))
        self.clearBtn.clicked.connect(lambda: self.clear())

        # 笔触颜色样式
        self.colorForm1 = QLabel()
        self.colorForm1.setObjectName('colorLabel1')
        self.colorForm2 = QLabel()
        self.colorForm2.setObjectName('colorLabel2')
        self.colorForm3 = QLabel()
        self.colorForm3.setObjectName('colorLabel3')
        self.colorForm4 = QLabel()
        self.colorForm4.setObjectName('colorLabel4')
        self.colorForm5 = QLabel()
        self.colorForm5.setObjectName('colorLabel5')
        self.colorForm6 = QLabel()
        self.colorForm6.setObjectName('colorLabel6')
        self.colorForm7 = QLabel()
        self.colorForm7.setObjectName('colorLabel7')

        # 调色板
        self.colorControlPad = QPushButton()
        self.colorControlPad.setObjectName('colorToolBtn')
        self.colorControlPad.setText('打开调色板')
        self.colorControlPad.clicked.connect(lambda: self.q_color_dialog())
        # 用于显示调色板选定的样式
        self.colorControlPadForm = QLabel()
        self.colorControlPadForm.setObjectName('colorStyle')
        self.colorControlPadForm.setStyleSheet('background-color:white')

        # 笔触大小
        self.label = QLabel('笔触样式大小')
        self.label.setObjectName('label')

        self.progressBar = QProgressBar()
        self.progressBar.setObjectName('progressBar')

        self.sizeLabel = QLabel('20')
        self.sizeLabel.setObjectName('label')

    def set_controlpanel_layout(self):
        self.controlPanelLayout = QVBoxLayout()
        self.controlPanel.setLayout(self.controlPanelLayout)

        self.controlPanelLayout.addWidget(self.buttonWidget, 1)
        self.controlPanelLayout.addWidget(self.viewBox, 1)

        # buttonWidget
        self.buttonWidgetLayout = QGridLayout()
        self.buttonWidget.setLayout(self.buttonWidgetLayout)

        self.buttonWidgetLayout.addWidget(self.resumeBtn, 0, 0)
        self.buttonWidgetLayout.addWidget(self.cancelBtn, 0, 1)
        self.buttonWidgetLayout.addWidget(self.clearBtn, 0, 2)

        self.buttonWidgetLayout.addWidget(self.radioButton1, 1, 0, 1, 4)
        self.buttonWidgetLayout.addWidget(self.colorForm1, 2, 0)
        self.buttonWidgetLayout.addWidget(self.colorForm2, 2, 1)
        self.buttonWidgetLayout.addWidget(self.colorForm3, 2, 2)
        self.buttonWidgetLayout.addWidget(self.colorForm4, 2, 3)
        self.buttonWidgetLayout.addWidget(self.colorForm5, 2, 4)
        self.buttonWidgetLayout.addWidget(self.colorForm6, 2, 5)
        self.buttonWidgetLayout.addWidget(self.colorForm7, 2, 6)

        self.buttonWidgetLayout.addWidget(self.radioButton2, 3, 0, 1, 4)
        self.buttonWidgetLayout.addWidget(self.colorControlPad, 4, 0, 1, 2)
        self.buttonWidgetLayout.addWidget(self.colorControlPadForm, 4, 2)

        self.buttonWidgetLayout.addWidget(self.label, 5, 0, 1, 3)
        self.buttonWidgetLayout.addWidget(self.progressBar, 6, 0, 1, 6)
        self.buttonWidgetLayout.addWidget(self.sizeLabel, 6, 6)

        self.viewBoxLayout = QHBoxLayout()
        self.viewBox.setLayout(self.viewBoxLayout)
        self.viewBoxLayout.addWidget(self.viewLabel)

    def set_form_layout(self):
        self.allLayout = QVBoxLayout()
        self.setLayout(self.allLayout)

        self.writinglayout = QHBoxLayout()
        self.frame1.setLayout(self.writinglayout)

        self.allLayout.addWidget(self.resultFrame, 1)
        self.allLayout.addWidget(self.frame1, 2)

        self.writinglayout.addWidget(self.writingPad, 7)
        self.writinglayout.addWidget(self.controlPanel, 2)

        self.resultFrameLayout = QHBoxLayout()
        self.resultFrame.setLayout(self.resultFrameLayout)
        self.resultFrameLayout.addWidget(self.textEdit)

    # ***********************业务逻辑*******************************
    def resume(self):
        pass

    def cancel(self):
        pass

    def clear(self):
        self.writingPad.clear()

    def set_color(self):
        pass

    def q_color_dialog(self):
        color = QColorDialog.getColor()
        self.penColor = color.name()
        self.colorControlPadForm.setStyleSheet('background-color:' +
                                               self.penColor)
Beispiel #25
0
class MyRecurrenceBox(QFrame):
    # TODO - Build a occurrence selector for Contract model based on spinbox
    # Used information type is DateTime.TimeDelta

    valueSet = pyqtSignal(bool)
    _recurrenceValue = None

    def __init__(self, *args):
        super(MyRecurrenceBox, self).__init__(*args)
        Lumberjack.info('spawning a << MyRecurrenceBox >>')
        _translate = QCoreApplication.translate

        self.setFrameShape(QFrame.StyledPanel)
        self.setFrameShadow(QFrame.Raised)
        self.verticalLayout = QVBoxLayout(self)
        self.verticalLayout.setObjectName("verticalLayout")

        self.spinBox = QSpinBox(self)
        self.spinBox.setObjectName("spinBox")
        self.spinBox.setValue(1)
        self.verticalLayout.addWidget(self.spinBox)
        self.spinBox.valueChanged.connect(self.on_value_spin)

        self.horizontalLayout_2 = QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")

        self.dailyRadioButton = QRadioButton(self)
        self.dailyRadioButton.setObjectName("dailyRadioButton")
        self.horizontalLayout_2.addWidget(self.dailyRadioButton)
        self.dailyRadioButton.setText(_translate("Form", "Days"))
        self.dailyRadioButton.setChecked(True)
        self.selected_radio_button = self.dailyRadioButton
        self.dailyRadioButton.toggled.connect(self.on_radio_toggle)

        self.weeklyRadioButton = QRadioButton(self)
        self.weeklyRadioButton.setObjectName("weeklyRadioButton")
        self.horizontalLayout_2.addWidget(self.weeklyRadioButton)
        self.weeklyRadioButton.setText(_translate("Form", "Weeks"))
        self.weeklyRadioButton.toggled.connect(self.on_radio_toggle)

        self.monthlyRadioButton = QRadioButton(self)
        self.monthlyRadioButton.setObjectName("monthlyRadioButton")
        self.horizontalLayout_2.addWidget(self.monthlyRadioButton)
        self.monthlyRadioButton.setText(_translate("Form", "Months"))
        self.monthlyRadioButton.toggled.connect(self.on_radio_toggle)

        self.yearlyRadioButton = QRadioButton(self)
        self.yearlyRadioButton.setObjectName("yearlyRadioButton")
        self.horizontalLayout_2.addWidget(self.yearlyRadioButton)
        self.verticalLayout.addLayout(self.horizontalLayout_2)
        self.yearlyRadioButton.setText(_translate("Form", "Years"))
        self.yearlyRadioButton.toggled.connect(self.on_radio_toggle)

        self.radio_buttons = [self.dailyRadioButton,
                              self.weeklyRadioButton,
                              self.monthlyRadioButton,
                              self.yearlyRadioButton]

    def getRecurrenceValue(self):
        Lumberjack.info('< MyRecurrenceBox > - -> (getRecurrenceValue)')
        return self._recurrenceValue

    def setRecurrenceValue(self, rel_delta):
        Lumberjack.info('< MyRecurrenceBox > - -> (setRecurrenceValue)')
        self._recurrenceValue = rel_delta
        Lumberjack.debug('(setRecurrenceValue) - rel_delta = {}'.format(rel_delta))
        if rel_delta is None:
            self._recurrenceValue = None
        else:
            for kw in rel_delta:
                for radio_button in self.radio_buttons:
                    if kw == radio_button.text().lower():
                        Lumberjack.debug('(setRecurrenceValue) - checking radiobutton = {}'.format(radio_button.text()))
                        radio_button.setChecked(True)
                        self.spinBox.setValue(rel_delta[kw])

        if self._recurrenceValue is None:
            self.valueSet.emit(False)
        else:
            self.valueSet.emit(True)

    recurrenceValue = pyqtProperty(dict, fget=getRecurrenceValue, fset=setRecurrenceValue)

    def on_radio_toggle(self, *args):
        Lumberjack.info('< MyRecurrenceBox > - -> (on_radio_toggle)')
        activate = args[0]
        Lumberjack.debug('(on_toggle) - args = {}'.format(activate))
        if not activate:
            return

        for radio_button in self.radio_buttons:
            if radio_button.isChecked():
                self.selected_radio_button = radio_button
                Lumberjack.debug('(on_toggle) - selected radiobutton.text = {}'.format(radio_button.text()))
        rel_delta = self._calculate_value()
        self._recurrenceValue = rel_delta

    def on_value_spin(self, x):
        Lumberjack.info('< MyRecurrenceBox > - -> (on_value_spin)')
        rel_delta = self._calculate_value()
        self._recurrenceValue = rel_delta

    def _calculate_value(self):
        Lumberjack.info('< MyRecurrenceBox > - -> (_calculate_value)')
        x = self.spinBox.value()
        kw = self.selected_radio_button.text().lower()
        timespan = {kw: x}
        Lumberjack.debug('(_calculate_value) - calculated value = {} {}'.format(timespan, type(timespan)))
        return timespan
Beispiel #26
0
class IcerikWidget(QWidget):
    def __init__(self, parent=None, name=""):
        super(IcerikWidget, self).__init__(parent)

        self.parent = parent
        self.name = "icerik/" + name + ".json"
        self.init_ui()

    def init_ui(self):

        with open(self.name, "r") as file:
            self.json_veri = file.read()
        self.json_veriq = json.loads(self.json_veri)
        self.aktifSoru = 0
        self.area = QScrollArea()
        self.area.setAlignment(Qt.AlignCenter)
        self.area.setWidgetResizable(True)
        self.area.setMaximumHeight(300)
        self.area.setMinimumHeight(150)

        self.metin = QLabel(
            self.json_veriq["sorular"][self.aktifSoru]["metin"])
        self.metin.setWordWrap(True)

        self.metin.setAlignment(Qt.AlignVCenter)
        self.metin.setObjectName("metin_icerik")
        self.metin.setTextInteractionFlags(Qt.TextSelectableByMouse)

        self.metin.setFont(QFont("Handlee", 16))
        self.area.setWidget(self.metin)

        self.soru = QLabel(self.json_veriq["sorular"][self.aktifSoru]["soru"])
        self.soru.setObjectName("soru")
        self.soru.setAlignment(Qt.AlignCenter)
        self.soru.setTextInteractionFlags(Qt.TextSelectableByMouse)

        self.form = QFormLayout()
        self.sik_0 = QRadioButton(
            self.json_veriq["sorular"][self.aktifSoru]["siklar"][0])
        self.sik_0.setObjectName("0")
        self.sik_1 = QRadioButton(
            self.json_veriq["sorular"][self.aktifSoru]["siklar"][1])
        self.sik_1.setObjectName("1")
        self.sik_2 = QRadioButton(
            self.json_veriq["sorular"][self.aktifSoru]["siklar"][2])
        self.sik_2.setObjectName("2")
        self.sik_3 = QRadioButton(
            self.json_veriq["sorular"][self.aktifSoru]["siklar"][3])
        self.sik_3.setObjectName("3")

        self.form.addRow(self.sik_0)
        self.form.addRow(self.sik_1)
        self.form.addRow(self.sik_2)
        self.form.addRow(self.sik_3)

        self.next = QPushButton("İleri")
        self.next.setIcon(QIcon("icon/next.png"))
        self.back = QPushButton("Geri")
        self.back.setIcon(QIcon("icon/back.png"))

        self.progres = QProgressBar()
        self.progres.setMaximum(len(self.json_veriq["sorular"]) - 1)
        self.progres.setMinimum(0)
        self.progres.setValue(self.aktifSoru)

        self.hb = QHBoxLayout()
        self.hb.addWidget(self.back)
        self.hb.addStretch()
        self.hb.addWidget(self.next)

        self.sonuc = QLabel("başarısız oldu")
        self.sonuc.setObjectName("sonuc")

        self.sonuc.setPixmap(QPixmap("icon/locked.png"))
        self.sonuc.setAlignment(Qt.AlignCenter)

        self.v_box1 = QVBoxLayout()

        self.v_box1.addWidget(self.area)
        self.v_box1.addStretch()
        self.v_box1.addWidget(self.soru)
        self.v_box1.addStretch()
        self.v_box1.addLayout(self.form)
        self.v_box1.addWidget(self.sonuc)

        self.l_vBox = QVBoxLayout()
        self.l_vBox.addLayout(self.v_box1)
        self.l_vBox.addStretch()
        self.l_vBox.addLayout(self.hb)
        self.l_vBox.addWidget(self.progres)

        self.setLayout(self.l_vBox)

        self.next.clicked.connect(self.ileri)
        self.back.clicked.connect(self.geri)
        self.sik_0.clicked.connect(self.secildi)
        self.sik_1.clicked.connect(self.secildi)
        self.sik_2.clicked.connect(self.secildi)
        self.sik_3.clicked.connect(self.secildi)

    def ileri(self):

        if self.aktifSoru < len(self.json_veriq["sorular"]) - 1:

            self.aktifSoru += 1

            self.metin.setText(
                self.json_veriq["sorular"][self.aktifSoru]["metin"])
            self.soru.setText(
                self.json_veriq["sorular"][self.aktifSoru]["soru"])
            self.sik_0.setText(
                self.json_veriq["sorular"][self.aktifSoru]["siklar"][0])
            self.sik_1.setText(
                self.json_veriq["sorular"][self.aktifSoru]["siklar"][1])
            self.sik_2.setText(
                self.json_veriq["sorular"][self.aktifSoru]["siklar"][2])
            self.sik_3.setText(
                self.json_veriq["sorular"][self.aktifSoru]["siklar"][3])
            self.sifirla()
            self.progres.setValue(self.aktifSoru)

    def geri(self):

        if not self.aktifSoru == 0:

            self.aktifSoru -= 1

            self.metin.setText(
                self.json_veriq["sorular"][self.aktifSoru]["metin"])
            self.soru.setText(
                self.json_veriq["sorular"][self.aktifSoru]["soru"])
            self.sik_0.setText(
                self.json_veriq["sorular"][self.aktifSoru]["siklar"][0])

            self.sik_1.setText(
                self.json_veriq["sorular"][self.aktifSoru]["siklar"][1])
            self.sik_2.setText(
                self.json_veriq["sorular"][self.aktifSoru]["siklar"][2])
            self.sik_3.setText(
                self.json_veriq["sorular"][self.aktifSoru]["siklar"][3])

            self.sifirla()
            self.progres.setValue(self.aktifSoru)

    def secildi(self):
        self.secilen = self.sender().objectName()

        self.dogru_sik = self.json_veriq["sorular"][
            self.aktifSoru]["dogruindex"]
        if self.secilen == self.dogru_sik:
            self.sonuc.setPixmap(QPixmap("icon/success.png"))
            self.sender().setStyleSheet(
                "background-color:rgba(27, 58, 27, 0.658)")
            self.metin.setStyleSheet(
                "background-color:rgba(27, 58, 27, 0.658)")
        else:
            self.sonuc.setPixmap(QPixmap("icon/error.png"))
            self.sender().setStyleSheet(
                "background-color: rgba(58, 27, 27, 0.658)")
            self.metin.setStyleSheet(
                "background-color: rgba(58, 27, 27, 0.658)")

    def sifirla(self):
        self.sik_0.setCheckable(False)
        self.sik_0.setCheckable(True)
        self.sik_0.setStyleSheet(
            "outline: none; color: #212222; margin-bottom: 2px;border: 2px solid rgba(0, 0, 0, 0.2); color: rgb(255, 255, 255);"
        )
        self.sik_1.setCheckable(False)
        self.sik_1.setCheckable(True)
        self.sik_1.setStyleSheet(
            "outline: none; color: #212222; margin-bottom: 2px;border: 2px solid rgba(0, 0, 0, 0.2); color: rgb(255, 255, 255);"
        )
        self.sik_2.setCheckable(False)
        self.sik_2.setCheckable(True)
        self.sik_2.setStyleSheet(
            "outline: none; color: #212222; margin-bottom: 2px;border: 2px solid rgba(0, 0, 0, 0.2); color: rgb(255, 255, 255);"
        )
        self.sik_3.setCheckable(False)
        self.sik_3.setCheckable(True)
        self.sik_3.setStyleSheet(
            "outline: none; color: #212222; margin-bottom: 2px;border: 2px solid rgba(0, 0, 0, 0.2); color: rgb(255, 255, 255);"
        )
        self.sonuc.setPixmap(QPixmap("icon/locked.png"))
        self.metin.setStyleSheet("background-color: rgb(29, 29, 29);")
Beispiel #27
0
class PreviewWidgetStyle(QGroupBox):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setTitle(self.tr("Preview"))
        self.setMaximumHeight(220)
        self.setObjectName("groupBox")

        self.verticalLayout = QVBoxLayout(self)
        self.verticalLayout.setObjectName("verticalLayout")

        self.tabWidget = QTabWidget(self)
        self.tabWidget.setObjectName("tabWidgetPreview")

        self.tab = QWidget()
        self.tab.setObjectName("tab")

        self.horizontalLayout = QHBoxLayout(self.tab)
        self.horizontalLayout.setObjectName("horizontalLayout")

        self.groupBox = QGroupBox(self.tab)
        self.groupBox.setTitle(self.tr("Group Box"))
        self.groupBox.setObjectName("groupBox")


        self.verticalLayout_2 = QVBoxLayout(self.groupBox)
        self.verticalLayout_2.setObjectName("verticalLayout_2")

        self.radioButton = QRadioButton(self.groupBox)
        self.radioButton.setText(self.tr("Radio Button"))
        self.radioButton.setChecked(True)
        self.radioButton.setObjectName("radioButton")
        self.verticalLayout_2.addWidget(self.radioButton)

        self.radioButton_2 = QRadioButton(self.groupBox)
        self.radioButton_2.setText(self.tr("Radio Button"))
        self.radioButton_2.setObjectName("radioButton_2")
        self.verticalLayout_2.addWidget(self.radioButton_2)

        self.line = QFrame(self.groupBox)
        self.line.setFrameShape(QFrame.HLine)
        self.line.setFrameShadow(QFrame.Sunken)
        self.line.setObjectName("line")
        self.verticalLayout_2.addWidget(self.line)

        self.checkBox = QCheckBox(self.groupBox)
        self.checkBox.setText(self.tr("Check Box"))
        self.checkBox.setChecked(True)
        self.checkBox.setObjectName("checkBox")
        self.verticalLayout_2.addWidget(self.checkBox)

        self.horizontalLayout.addWidget(self.groupBox)


        self.verticalLayout_3 = QVBoxLayout()
        self.verticalLayout_3.setObjectName("verticalLayout_3")

        self.progressBar = QProgressBar(self.tab)
        self.progressBar.setProperty("value", 75)
        self.progressBar.setObjectName("progressBar")
        self.verticalLayout_3.addWidget(self.progressBar)

        self.horizontalSlider = QSlider(self.tab)
        self.horizontalSlider.setProperty("value", 45)
        self.horizontalSlider.setSliderPosition(45)
        self.horizontalSlider.setOrientation(Qt.Horizontal)
        self.horizontalSlider.setObjectName("horizontalSlider")
        self.verticalLayout_3.addWidget(self.horizontalSlider)

        self.horizontalLayout_2 = QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")

        self.spinBox = QSpinBox(self.tab)
        self.spinBox.setObjectName("spinBox")
        self.horizontalLayout_2.addWidget(self.spinBox)

        self.pushButton = QPushButton(self.tab)
        self.pushButton.setText(self.tr("Button"))
        self.pushButton.setObjectName("pushButton")
        self.horizontalLayout_2.addWidget(self.pushButton)

        self.verticalLayout_3.addLayout(self.horizontalLayout_2)

        self.comboBox = QComboBox(self.tab)
        self.comboBox.setObjectName("comboBox")
        self.comboBox.addItem(self.tr("Combo Box"))
        self.verticalLayout_3.addWidget(self.comboBox)

        self.horizontalLayout.addLayout(self.verticalLayout_3)

        self.verticalScrollBar = QScrollBar(self.tab)
        self.verticalScrollBar.setPageStep(50)
        self.verticalScrollBar.setOrientation(Qt.Vertical)
        self.verticalScrollBar.setObjectName("verticalScrollBar")
        self.horizontalLayout.addWidget(self.verticalScrollBar)
        self.tabWidget.addTab(self.tab, self.tr("Tab 1"))


        self.tab_2 = QWidget()
        self.tab_2.setObjectName("tab_2")
        self.tabWidget.addTab(self.tab_2, self.tr("Tab 2"))

        self.verticalLayout.addWidget(self.tabWidget)

        self.pushButton.installEventFilter(self)
        self.pushButton.setFocusPolicy(Qt.NoFocus)
        self.radioButton.installEventFilter(self)
        self.radioButton.setFocusPolicy(Qt.NoFocus)
        self.radioButton_2.installEventFilter(self)
        self.radioButton_2.setFocusPolicy(Qt.NoFocus)
        self.checkBox.installEventFilter(self)
        self.checkBox.setFocusPolicy(Qt.NoFocus)
        self.comboBox.installEventFilter(self)
        self.comboBox.setFocusPolicy(Qt.NoFocus)
        self.spinBox.installEventFilter(self)
        self.spinBox.setFocusPolicy(Qt.NoFocus)
        self.horizontalSlider.installEventFilter(self)
        self.horizontalSlider.setFocusPolicy(Qt.NoFocus)
        self.verticalScrollBar.installEventFilter(self)
        self.verticalScrollBar.setFocusPolicy(Qt.NoFocus)
        self.tab.installEventFilter(self)
        self.tab.setFocusPolicy(Qt.NoFocus)
        self.tab_2.installEventFilter(self)
        self.tab_2.setFocusPolicy(Qt.NoFocus)
        self.tabWidget.installEventFilter(self)
        self.tabWidget.setFocusPolicy(Qt.NoFocus)

        self.tabWidget.currentChanged.connect(self.noClick)

    def noClick(self, x):
        self.tabWidget.setCurrentIndex(0)

    def eventFilter(self, obj, event):
        if self.pushButton:
            if event.type() == QEvent.MouseButtonRelease:
                return True
            elif event.type() == QEvent.MouseButtonPress:
                return True
            elif event.type() == QEvent.MouseButtonDblClick:
                return True
            else:
                return False
        else:
            super().eventFilter(obj, event)
Beispiel #28
0
class UiYoutube(PageWindow):  # Youtube UI and Youtube Download Manager
    def __init__(self):
        super().__init__()
        self.initUI()
        self.setWindowTitle("Youtube Downloader")

    def initUI(self):
        self.setupUi(self)

    def UiTest(self):  # Used for testing UI
        self.progressBar.setVisible(True)
        self.pushButton.setVisible(False)
        self.groupBox_for_videoFormats.setVisible(False)
        self.groupBox_for_typeSelection.setVisible(False)
        self.label_for_SizeDisplay.setVisible(True)
        self.label_for_FilenameDisplay.setVisible(True)

    def type_vid(self):  # Executed, if the type video is selected
        """ Changes the UI for video downloading """
        self.groupBox_for_typeSelection.setVisible(False)
        self.groupBox_for_videoFormats.setVisible(True)
        self.resolution_comboBox.setVisible(True)
        self.pushButton.setVisible(True)
        self.progressive_checkbox.setVisible(True)
        QMessageBox.question(
            self, 'NOTE',
            "HD Videos are stored separately as Audio and Only Video "
            "formats in youtube.\nUse High"
            " resolution option to download HD video and combine it with"
            " audio with FFMPEG for best result.\n**-->>SD(480p-) videos "
            "are available in combined form.", QMessageBox.Ok)
        TYPE = "video"
        data.add('type', TYPE)
        print('Type -> video proceeding to qual,format setup')

    def type_aud(self):  # Executed, if the type Audio is selected
        """ Establishes connection and downloads audio """
        print('Type audio -> ask loc and start download')
        TYPE = "audio"
        data.add('type', TYPE)
        self.groupBox_for_typeSelection.setVisible(False)
        self.Title_label.setText('PLEASE WAIT...\nStarting Download..')
        path_to_save = QFileDialog.getExistingDirectory()
        print(path_to_save)
        data.add('loc', path_to_save)
        print(data, '@ type aud')
        try:
            yt = YouTube(data.get('url'))
            aud_stream = yt.streams.filter(type='audio').first(
            )  # Establish connection and gets audio stream
        except:
            print('OOPs!')
            QMessageBox.question(self, 'ELITE', 'Server Connection Failed!!',
                                 QMessageBox.Ok)
            exit(0)
        if aud_stream is None:  # Check if audio stream is available
            print('SGS_ERROR-404_NO_STREAM')
            QMessageBox.question(
                self, 'ELITE', 'Selected Stream not available\nPing Streams'
                ' from other menu or retry a different stream', QMessageBox.Ok)
            exit(0)
        else:
            try:
                aud_stream.download(str(
                    data.get('loc')))  # Download in given location
                print('SGS_CODE_SUCCESS')
                QMessageBox.question(self, 'ELITE', 'Download succesful !!!',
                                     QMessageBox.Ok)
            except:
                print('ERROR_IN_DOWNLOAD')
                QMessageBox.question(self, 'ELITE', 'Download Failed !!!',
                                     QMessageBox.Ok)
                exit(0)
        exit(0)

    def progress_check(self, stream=None, chunk=None, remaining=None):
        """ Computes percentage for displaying in progressbar """
        percentage = (100 * (data.get('size') - remaining)) / data.get('size')
        self.progressBar.setValue(int(percentage))

    def download_manager_vid(self):  # Downloads Youtube videos
        """ Establishes connection and selects reqd. stream and downloads it """
        try:
            yt = YouTube(data.get('url'),
                         on_progress_callback=self.progress_check)
        except:
            print('internet??')
            return 'Server Connection failed! \nCheck Internet and URL'
        resolution = data.get('qual')
        format = data.get('format')
        path = data.get('loc')
        Progressive_or_not = data.get('ext')
        if Progressive_or_not:
            if resolution == 'any' and format == 'mp4':
                self.selected_stream = yt.streams.filter(
                    progressive=Progressive_or_not,
                    file_extension=format).order_by('resolution').last()
            elif format == 'any' and resolution == 'any':
                self.selected_stream = yt.streams.filter(
                    progressive=Progressive_or_not).order_by(
                        'resolution').last()
            else:
                self.selected_stream = yt.streams.filter(
                    progressive=Progressive_or_not,
                    file_extension=format).get_by_resolution(resolution)
        if not Progressive_or_not:
            if resolution == 'any' and format == 'mp4':
                self.selected_stream = yt.streams.filter(
                    type='video',
                    file_extension=format).order_by('resolution').last()
            elif format == 'any' and resolution == 'any':
                self.selected_stream = yt.streams.filter(
                    type='video').order_by('resolution').last()
            else:
                self.selected_stream = yt.streams.filter(
                    file_extension=format).get_by_resolution(resolution)
        if self.selected_stream is None:
            print('SGS_ERROR-404_NO_STREAM')
            return 'Selected Stream not available\nPing Streams' + 'from other menu or retry a different stream'
        data.add('size', self.selected_stream.filesize)
        self.selected_stream.download(path)
        print('SGS_CODE_SUCCESS')
        return 'Download Successful !!'

    def get_VideoSpecs(self):
        """Gets Video specifications and location and adjusts UI accordingly"""
        if self.mp4_radioButton.isChecked():
            print('Mp4 is selected -- proceed 147')
            data.add('format', 'mp4')
        elif self.webm_radioButton.isChecked():
            print('WEBM is selected -- proceed 149')
            data.add('format', 'webm')
        else:
            data.add('format', 'any')
        QUALITY = str(self.resolution_comboBox.currentText())
        data.add('qual', QUALITY)
        if self.progressive_checkbox.isChecked():
            data.add('ext', False)
            print('Progressive - False')
        else:
            data.add('ext', True)
            print('Progressive - True')
        print(data.get('format'), data.get('qual'), data.get('ext'),
              "End of info collection")
        self.groupBox_for_videoFormats.setVisible(False)
        self.pushButton.setVisible(False)
        self.progressive_checkbox.setVisible(False)
        self.resolution_comboBox.setVisible(False)
        self.Title_label.setText('PLEASE WAIT...\nStarting Download...')
        self.Title_label.setVisible(True)
        try:
            yt = YouTube(data.get('url'))
        except:
            QMessageBox.question(
                self, 'ELITE',
                'Server Connection Failed!!\nCheck url or Internet',
                QMessageBox.Ok)
            print('internet??')
            exit(0)
        resolution = data.get('qual')
        format = data.get('format')
        Progressive_or_not = data.get('ext')
        if Progressive_or_not:
            if resolution == 'any' and format == 'mp4':
                selected_stream = yt.streams.filter(
                    progressive=Progressive_or_not,
                    file_extension=format).order_by('resolution').last()
            elif format == 'any' and resolution == 'any':
                selected_stream = yt.streams.filter(
                    progressive=Progressive_or_not).order_by(
                        'resolution').last()
            else:
                selected_stream = yt.streams.filter(
                    progressive=Progressive_or_not,
                    file_extension=format).get_by_resolution(resolution)
        if not Progressive_or_not:
            if resolution == 'any' and format == 'mp4':
                selected_stream = yt.streams.filter(
                    type='video',
                    file_extension=format).order_by('resolution').last()
            elif format == 'any' and resolution == 'any':
                selected_stream = yt.streams.filter(
                    type='video').order_by('resolution').last()
            else:
                selected_stream = yt.streams.filter(
                    file_extension=format).get_by_resolution(resolution)
        if selected_stream is None:
            QMessageBox.question(
                self, 'ELITE', 'Selected Stream not available\nPing Streams'
                ' from other menu or retry a different stream', QMessageBox.Ok)
            print('SGS_ERROR-404_NO_STREAM @ 484')
            exit(0)
        filesize = (selected_stream.filesize) * (10**-6)
        filename = selected_stream.default_filename
        self.label_for_SizeDisplay.setText("FILE SIZE: " +
                                           str(round(filesize, 2)) + ' MB')
        self.label_for_SizeDisplay.setVisible(True)
        self.label_for_FilenameDisplay.setText('VIDEO NAME: ' + str(filename))
        self.label_for_FilenameDisplay.setVisible(True)
        self.progressBar.setVisible(True)
        self.pushButton_.setVisible(False)
        path_to_save = QFileDialog.getExistingDirectory(self)
        print(path_to_save)
        data.add('loc', path_to_save)
        print(data)
        message_from_func = self.download_manager_vid()
        QMessageBox.question(self, 'ELITE', message_from_func, QMessageBox.Ok)
        exit(0)

    def setupUi(self, youtube_setup):
        """Sets up the page UI"""
        youtube_setup.setObjectName("youtube_setup")
        self.centralwidget = QWidget(youtube_setup)
        self.centralwidget.setObjectName("centralwidget")
        self.resolution_comboBox = QComboBox(self.centralwidget)
        self.resolution_comboBox.setGeometry(QRect(410, 110, 100, 33))
        self.resolution_comboBox.setObjectName("resolution_comboBox")
        list_quality = ['any', '240p', '360p', '720p', '1080p']
        self.resolution_comboBox.addItems(list_quality)
        self.resolution_comboBox.setVisible(False)
        self.progressive_checkbox = QCheckBox(self.centralwidget)
        self.progressive_checkbox.setGeometry(QRect(20, 230, 350, 50))
        self.progressive_checkbox.setObjectName("check_box")
        self.progressive_checkbox.setVisible(False)
        self.Title_label = QLabel(self.centralwidget)
        self.Title_label.setGeometry(QRect(170, 10, 261, 51))
        self.label_for_SizeDisplay = QLabel(self.centralwidget)
        self.label_for_SizeDisplay.setGeometry(QRect(160, 160, 180, 41))
        self.label_for_SizeDisplay.setObjectName("label_for_SizeDisplay")
        self.label_for_SizeDisplay.setVisible(False)
        self.label_info = QLabel(self.centralwidget)
        self.label_info.setGeometry(QRect(20, 310, 260, 20))
        self.label_info.setObjectName("label_info")
        font = QFont()
        font.setPointSize(14)
        font.setBold(True)
        font.setItalic(True)
        font.setWeight(75)
        self.Title_label.setFont(font)
        self.Title_label.setObjectName("Title_label")
        self.groupBox_for_typeSelection = QGroupBox(self.centralwidget)
        self.groupBox_for_typeSelection.setGeometry(QRect(200, 90, 191, 121))
        self.groupBox_for_typeSelection.setObjectName(
            "groupBox_for_typeSelection")
        self.type_audio_radioButton = QRadioButton(
            self.groupBox_for_typeSelection)
        self.type_audio_radioButton.setGeometry(QRect(40, 40, 104, 23))
        self.type_audio_radioButton.setObjectName("type_audio_radioButton")
        self.type_audio_radioButton.clicked.connect(lambda: self.type_aud())
        self.type_video_radioButton = QRadioButton(
            self.groupBox_for_typeSelection)
        self.type_video_radioButton.setGeometry(QRect(40, 70, 104, 23))
        self.type_video_radioButton.setObjectName("type_video_radioButton")
        self.type_video_radioButton.clicked.connect(lambda: self.type_vid())
        self.pushButton = QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QRect(460, 290, 88, 33))
        self.pushButton.setObjectName("pushButton")
        self.pushButton.setVisible(False)
        self.pushButton.clicked.connect(lambda: self.get_VideoSpecs())
        self.pushButton_ = QPushButton(self.centralwidget)
        self.pushButton_.setGeometry(QRect(460, 290, 88, 33))
        self.pushButton_.setObjectName("pushButton")
        self.pushButton_.setVisible(False)
        self.pushButton_.clicked.connect(
            lambda: self.YoutubeManager.download_manager_vid(self))
        self.groupBox_for_videoFormats = QGroupBox(self.centralwidget)
        self.groupBox_for_videoFormats.setGeometry(QRect(200, 90, 141, 111))
        self.groupBox_for_videoFormats.setObjectName(
            "groupBox_for_videoFormats")
        self.groupBox_for_videoFormats.setVisible(False)
        self.mp4_radioButton = QRadioButton(self.groupBox_for_videoFormats)
        self.mp4_radioButton.setGeometry(QRect(20, 30, 104, 23))
        self.mp4_radioButton.setObjectName("mp4_radioButton")
        self.webm_radioButton = QRadioButton(self.groupBox_for_videoFormats)
        self.webm_radioButton.setGeometry(QRect(20, 60, 104, 23))
        self.webm_radioButton.setObjectName("webm_radioButton")
        self.progressBar = QProgressBar(self.centralwidget)
        self.progressBar.setGeometry(QRect(90, 230, 391, 23))
        self.progressBar.setProperty("value", 24)
        self.progressBar.setObjectName("progressBar")
        self.progressBar.setVisible(False)
        self.label_for_FilenameDisplay = QLabel(self.centralwidget)
        self.label_for_FilenameDisplay.setGeometry(QRect(75, 110, 500, 50))
        self.label_for_FilenameDisplay.setObjectName(
            "label_for_FilenameDisplay")
        self.label_for_FilenameDisplay.setVisible(False)
        youtube_setup.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(youtube_setup)
        self.menubar.setGeometry(QRect(0, 0, 586, 25))
        self.menubar.setObjectName("menubar")
        youtube_setup.setMenuBar(self.menubar)
        self.progressBar.setValue(0)
        self.statusbar = QStatusBar(youtube_setup)
        self.statusbar.setObjectName("statusbar")
        youtube_setup.setStatusBar(self.statusbar)

        self.retranslateUi(youtube_setup)
        QMetaObject.connectSlotsByName(youtube_setup)

    def retranslateUi(self, youtube_setup):
        _translate = QCoreApplication.translate
        youtube_setup.setWindowTitle(
            _translate("youtube_setup", "Youtube Video Download-ELITELOADER"))
        self.Title_label.setText(
            _translate("youtube_setup", "Select Format and Quality"))
        self.label_for_SizeDisplay.setText(_translate("ELITE", "SIZE:"))
        self.label_for_FilenameDisplay.setText(_translate(
            "ELITE", "FILENAME:"))
        self.groupBox_for_typeSelection.setTitle(
            _translate("youtube_setup", "Type"))
        self.progressive_checkbox.setText(
            _translate('youtube_setup', "High Resolution/Non-Progressive"))
        self.type_audio_radioButton.setText(
            _translate("youtube_setup", "Audio"))
        self.label_info.setText(
            _translate("StartPage_Url",
                       "*This checking process may take longer"))
        self.type_video_radioButton.setText(
            _translate("youtube_setup", "Video"))
        self.pushButton.setText(_translate("youtube_setup", "Proceed"))
        self.pushButton_.setText(_translate("youtube_setup", "Download"))
        self.groupBox_for_videoFormats.setTitle(
            _translate("youtube_setup", "Format"))
        self.mp4_radioButton.setText(_translate("youtube_setup", "MP4"))
        self.webm_radioButton.setText(_translate("youtube_setup", "WEBM"))

    class YoutubeManager:  # Manage Youtube Downloads
        def __init__(self):
            pass

        def ping(
                self):  # Check Available Streams and returns a list of streams
            try:
                yt = YouTube(data.get('url'))
                pingster = yt.streams.all()
                return pingster
            except:
                print('Error in connection')
                return 'Error in connection\nCheck URL and Internet'
class Window(QWidget):
    """
    Класс пользовательского интерфейса
    """
    def __init__(self):
        super(Window, self).__init__()

        self.render_area = RenderArea()

        self.tabs = QTabWidget(self)
        """
        Управление общими параметрами сферы
        """
        # Управляющий элемент для шага аппроксимации
        self.approximation_step_SpinBox = self.create_spinbox(1, 1, 50)
        self.approximation_step_Label = QLabel("Шаг аппроксимации:")
        self.approximation_step_Label.setBuddy(self.approximation_step_SpinBox)
        # Управляющий элемент для радиуса сферы
        self.radius_SpinBox = self.create_spinbox(30, 1, 50)
        self.radius_Label = QLabel("Радиус сферы:")
        self.radius_Label.setBuddy(self.radius_SpinBox)
        # Управляющие элементы для поворотов по осям
        self.x_rotate_Label = QLabel("Поворот по оси 0X")
        self.y_rotate_Label = QLabel("Поворот по оси 0Y")
        self.z_rotate_Label = QLabel("Поворот по оси 0Z")
        self.x_rotate_Slider = self.create_slider(0, 0, 360, 1, 60, 1)
        self.y_rotate_Slider = self.create_slider(0, 0, 360, 1, 60, 1)
        self.z_rotate_Slider = self.create_slider(0, 0, 360, 1, 60, 1)
        # Управляющие элементы для перемещения по осям
        self.x_move_Label = QLabel("Перемещение по оси 0X")
        self.y_move_Label = QLabel("Перемещение по оси 0Y")
        self.z_move_Label = QLabel("Перемещение по оси 0Z")
        self.x_move_Slider = self.create_slider(0, -300, 300, 1, 60, 1)
        self.y_move_Slider = self.create_slider(0, -300, 300, 1, 60, 1)
        self.z_move_Slider = self.create_slider(0, -300, 300, 1, 60, 1)
        # Управляющие элементы для масштабирования по осям
        self.x_scale_Label = QLabel("Масштабирование по оси 0X")
        self.y_scale_Label = QLabel("Масштабирование по оси 0Y")
        self.z_scale_Label = QLabel("Масштабирование по оси 0Z")
        self.x_scale_Slider = self.create_slider(1, 1, 10, 1, 60, 1)
        self.y_scale_Slider = self.create_slider(1, 1, 10, 1, 60, 1)
        self.z_scale_Slider = self.create_slider(1, 1, 10, 1, 60, 1)

        # Наполняем первый таб для интерфейса пользователя
        self.controls_layout = QGridLayout()
        self.controls_layout.addWidget(self.approximation_step_Label, 0, 0)
        self.controls_layout.addWidget(self.approximation_step_SpinBox, 0, 1)
        self.controls_layout.addWidget(self.radius_Label, 1, 0)
        self.controls_layout.addWidget(self.radius_SpinBox, 1, 1)
        self.controls_layout.addWidget(self.x_rotate_Label, 2, 0)
        self.controls_layout.addWidget(self.x_rotate_Slider, 2, 1)
        self.controls_layout.addWidget(self.y_rotate_Label, 3, 0)
        self.controls_layout.addWidget(self.y_rotate_Slider, 3, 1)
        self.controls_layout.addWidget(self.z_rotate_Label, 4, 0)
        self.controls_layout.addWidget(self.z_rotate_Slider, 4, 1)
        self.controls_layout.addWidget(self.x_move_Label, 5, 0)
        self.controls_layout.addWidget(self.x_move_Slider, 5, 1)
        self.controls_layout.addWidget(self.y_move_Label, 6, 0)
        self.controls_layout.addWidget(self.y_move_Slider, 6, 1)
        self.controls_layout.addWidget(self.z_move_Label, 7, 0)
        self.controls_layout.addWidget(self.z_move_Slider, 7, 1)
        self.controls_layout.addWidget(self.x_scale_Label, 8, 0)
        self.controls_layout.addWidget(self.x_scale_Slider, 8, 1)
        self.controls_layout.addWidget(self.y_scale_Label, 9, 0)
        self.controls_layout.addWidget(self.y_scale_Slider, 9, 1)
        self.controls_layout.addWidget(self.z_scale_Label, 10, 0)
        self.controls_layout.addWidget(self.z_scale_Slider, 10, 1)
        self.controls_layout.setRowStretch(11, 1)

        self.controls_widget = QWidget(self)
        self.controls_widget.setLayout(self.controls_layout)

        self.tabs.addTab(self.controls_widget, "Управление")
        """
        Управление проекциями
        """
        # Управляющие элементы для переключения проекций
        self.default_projection = QRadioButton('По умолчанию')
        self.front_projection = QRadioButton('Фронтальная')
        self.horizontal_projection = QRadioButton('Горизонтальная')
        self.profile_projection = QRadioButton('Профильная')
        self.axonometric_projection = QRadioButton('Аксонометрическая')
        self.oblique_projection = QRadioButton('Косоугольная')
        self.perspective_projection = QRadioButton('Перспективная')

        self.default_projection.setObjectName("default")
        self.front_projection.setObjectName("front")
        self.horizontal_projection.setObjectName("horizontal")
        self.profile_projection.setObjectName("profile")
        self.axonometric_projection.setObjectName("axonometric")
        self.oblique_projection.setObjectName("oblique")
        self.perspective_projection.setObjectName("perspective")

        self.default_projection.setChecked(True)

        # Настройки для аксонометрической проекции
        self.axonometric_fi_angle_Label = QLabel("Угол φ:")
        self.axonometric_fi_angle_SpinBox = self.create_spinbox(40, 0, 360)
        self.axonometric_fi_angle_Label.setBuddy(
            self.axonometric_fi_angle_SpinBox)

        self.axonometric_psi_angle_Label = QLabel("Угол ψ:")
        self.axonometric_psi_angle_SpinBox = self.create_spinbox(10, 0, 360)
        self.axonometric_psi_angle_Label.setBuddy(
            self.axonometric_psi_angle_SpinBox)

        # Косоугольная
        self.oblique_alpha_angle_Label = QLabel("Угол α:")
        self.oblique_alpha_angle_SpinBox = self.create_spinbox(20, 0, 360)
        self.oblique_alpha_angle_Label.setBuddy(
            self.oblique_alpha_angle_SpinBox)

        self.oblique_L_Label = QLabel("L:")
        self.oblique_L_SpinBox = self.create_double_spinbox(0.1, 0.01, 0.1, 50)
        self.oblique_L_Label.setBuddy(self.oblique_L_SpinBox)

        # Перспективная
        self.perspective_teta_angle_Label = QLabel("Угол θ:")
        self.perspective_teta_angle_SpinBox = self.create_spinbox(
            580, -1000, 1000)
        self.perspective_teta_angle_Label.setBuddy(
            self.perspective_teta_angle_SpinBox)

        self.perspective_fi_angle_Label = QLabel("Угол φ:")
        self.perspective_fi_angle_SpinBox = self.create_spinbox(
            -5, -1000, 1000)
        self.perspective_fi_angle_Label.setBuddy(
            self.perspective_fi_angle_SpinBox)

        self.perspective_d_Label = QLabel("d:")
        self.perspective_d_SpinBox = self.create_spinbox(250, -1000, 1000)
        self.perspective_d_Label.setBuddy(self.perspective_d_SpinBox)

        self.perspective_ro_Label = QLabel("ρ:")
        self.perspective_ro_SpinBox = self.create_spinbox(420, -1000, 1000)
        self.perspective_ro_Label.setBuddy(self.perspective_ro_SpinBox)

        # Наполняем второй таб для интерфейса пользователя
        self.projection_layout = QGridLayout()
        self.projection_layout.addWidget(self.default_projection, 0, 0)
        self.projection_layout.addWidget(self.front_projection, 1, 0)
        self.projection_layout.addWidget(self.horizontal_projection, 2, 0)
        self.projection_layout.addWidget(self.profile_projection, 3, 0)
        self.projection_layout.addWidget(self.axonometric_projection, 4, 0)
        self.projection_layout.addWidget(self.axonometric_fi_angle_Label, 5, 0)
        self.projection_layout.addWidget(self.axonometric_fi_angle_SpinBox, 5,
                                         1)
        self.projection_layout.addWidget(self.axonometric_psi_angle_Label, 5,
                                         2)
        self.projection_layout.addWidget(self.axonometric_psi_angle_SpinBox, 5,
                                         3)
        self.projection_layout.addWidget(self.oblique_projection, 6, 0)
        self.projection_layout.addWidget(self.oblique_alpha_angle_Label, 7, 0)
        self.projection_layout.addWidget(self.oblique_alpha_angle_SpinBox, 7,
                                         1)
        self.projection_layout.addWidget(self.oblique_L_Label, 7, 2)
        self.projection_layout.addWidget(self.oblique_L_SpinBox, 7, 3)
        self.projection_layout.addWidget(self.perspective_projection, 8, 0)
        self.projection_layout.addWidget(self.perspective_teta_angle_Label, 9,
                                         0)
        self.projection_layout.addWidget(self.perspective_teta_angle_SpinBox,
                                         9, 1)
        self.projection_layout.addWidget(self.perspective_fi_angle_Label, 9, 2)
        self.projection_layout.addWidget(self.perspective_fi_angle_SpinBox, 9,
                                         3)
        self.projection_layout.addWidget(self.perspective_d_Label, 10, 0)
        self.projection_layout.addWidget(self.perspective_d_SpinBox, 10, 1)
        self.projection_layout.addWidget(self.perspective_ro_Label, 10, 2)
        self.projection_layout.addWidget(self.perspective_ro_SpinBox, 10, 3)
        self.projection_layout.setRowStretch(11, 1)

        self.projection_widget = QWidget(self)
        self.projection_widget.setLayout(self.projection_layout)

        self.tabs.addTab(self.projection_widget, "Проекции")
        """
        Управление светом
        """
        # Управляющий элемент для ширины линии
        self.pen_width_SpinBox = self.create_spinbox(3, 0, 20)
        self.pen_width_Label = QLabel("Ширина линии:")
        self.pen_width_Label.setBuddy(self.pen_width_SpinBox)
        # Управляющие элементы для цвета линии
        self.pen_color_Label = QLabel("Цвет линии #000000")
        self.pen_color_Button = QPushButton("Изменить цвет линии")
        # Управляющий элемент для отсечения
        self.clipping_CheckBox = QCheckBox("Отсечение")
        self.clipping_CheckBox.setChecked(False)
        # Управляющие элементы для цвета объекта
        self.object_color_Label = QLabel("Цвет объекта #00ff00")
        self.object_color_Button = QPushButton("Изменить цвет объекта")
        # Управляющие элементы для положения источника света
        self.light_x_SpinBox = self.create_spinbox(0, -100, 100)
        self.light_x_Label = QLabel("X:")
        self.light_x_Label.setBuddy(self.light_x_SpinBox)
        self.light_y_SpinBox = self.create_spinbox(0, -100, 100)
        self.light_y_Label = QLabel("Y:")
        self.light_y_Label.setBuddy(self.light_y_SpinBox)
        self.light_z_SpinBox = self.create_spinbox(-1000, -100, 100)
        self.light_z_Label = QLabel("Z:")
        self.light_z_Label.setBuddy(self.light_z_SpinBox)
        # Группирующий элемент для управляющий светом элементов
        self.light_GroupBox = QGroupBox("Источник света")
        self.light_GroupBox.setCheckable(True)
        self.light_GroupBox_layout = QGridLayout(self)
        self.light_GroupBox_layout.addWidget(self.object_color_Label, 0, 0)
        self.light_GroupBox_layout.addWidget(self.object_color_Button, 0, 1)
        self.light_GroupBox_layout.addWidget(self.light_x_Label, 1, 0)
        self.light_GroupBox_layout.addWidget(self.light_x_SpinBox, 1, 1)
        self.light_GroupBox_layout.addWidget(self.light_y_Label, 2, 0)
        self.light_GroupBox_layout.addWidget(self.light_y_SpinBox, 2, 1)
        self.light_GroupBox_layout.addWidget(self.light_z_Label, 3, 0)
        self.light_GroupBox_layout.addWidget(self.light_z_SpinBox, 3, 1)
        self.light_GroupBox.setLayout(self.light_GroupBox_layout)

        # Наполняем третий таб для интерфейса пользователя
        self.light_layout = QGridLayout()
        self.light_layout.addWidget(self.pen_width_Label, 0, 0)
        self.light_layout.addWidget(self.pen_width_SpinBox, 0, 1)
        self.light_layout.addWidget(self.pen_color_Label, 1, 0)
        self.light_layout.addWidget(self.pen_color_Button, 1, 1)
        self.light_layout.addWidget(self.clipping_CheckBox, 2, 0)
        self.light_layout.addWidget(self.light_GroupBox, 3, 0, 1, 2)
        self.light_layout.setRowStretch(4, 1)

        self.light_widget = QWidget(self)
        self.light_widget.setLayout(self.light_layout)

        self.tabs.addTab(self.light_widget, "Свет")

        # splitter позволит пользователю изменять ширину колонок с настройками и графикой
        self.splitter = QSplitter(Qt.Horizontal)
        self.splitter.addWidget(self.tabs)
        self.splitter.addWidget(self.render_area)

        # Основной слой - тут то, что пользователю будет показано в интерфейсе
        main_layout = QHBoxLayout(self)
        main_layout.addWidget(self.splitter)
        self.setLayout(main_layout)

        self.make_widgets_connect()

        self.set_default_values()

        self.setWindowTitle("Аппроксимация сферы")

    def make_widgets_connect(self):
        """
        Осуществляет привязку сигналов от виджетов к слотам
        """
        self.pen_width_SpinBox.valueChanged.connect(
            self.render_area.set_pen_width)
        self.approximation_step_SpinBox.valueChanged.connect(
            self.render_area.sphere.set_approximation_step)
        self.radius_SpinBox.valueChanged.connect(
            self.render_area.sphere.set_radius)
        self.x_rotate_Slider.valueChanged.connect(
            self.render_area.sphere.set_x_rotate_angle)
        self.y_rotate_Slider.valueChanged.connect(
            self.render_area.sphere.set_y_rotate_angle)
        self.z_rotate_Slider.valueChanged.connect(
            self.render_area.sphere.set_z_rotate_angle)

        self.x_move_Slider.valueChanged.connect(
            self.render_area.sphere.set_x_move)
        self.y_move_Slider.valueChanged.connect(
            self.render_area.sphere.set_y_move)
        self.z_move_Slider.valueChanged.connect(
            self.render_area.sphere.set_z_move)

        self.x_scale_Slider.valueChanged.connect(
            self.render_area.sphere.set_x_scale)
        self.y_scale_Slider.valueChanged.connect(
            self.render_area.sphere.set_y_scale)
        self.z_scale_Slider.valueChanged.connect(
            self.render_area.sphere.set_z_scale)

        self.default_projection.toggled.connect(
            lambda: self.render_area.set_projection(self.default_projection))
        self.front_projection.toggled.connect(
            lambda: self.render_area.set_projection(self.front_projection))
        self.horizontal_projection.toggled.connect(
            lambda: self.render_area.set_projection(self.horizontal_projection
                                                    ))
        self.profile_projection.toggled.connect(
            lambda: self.render_area.set_projection(self.profile_projection))
        self.axonometric_projection.toggled.connect(
            lambda: self.render_area.set_projection(self.axonometric_projection
                                                    ))
        self.oblique_projection.toggled.connect(
            lambda: self.render_area.set_projection(self.oblique_projection))
        self.perspective_projection.toggled.connect(
            lambda: self.render_area.set_projection(self.perspective_projection
                                                    ))

        self.axonometric_fi_angle_SpinBox.valueChanged.connect(
            self.render_area.sphere.set_axonometric_angle_fi)
        self.axonometric_psi_angle_SpinBox.valueChanged.connect(
            self.render_area.sphere.set_axonometric_angle_psi)

        self.oblique_alpha_angle_SpinBox.valueChanged.connect(
            self.render_area.sphere.set_oblique_angle_alpha)
        self.oblique_L_SpinBox.valueChanged.connect(
            self.render_area.sphere.set_oblique_L)

        self.perspective_teta_angle_SpinBox.valueChanged.connect(
            self.render_area.sphere.set_perspective_angle_teta)
        self.perspective_fi_angle_SpinBox.valueChanged.connect(
            self.render_area.sphere.set_perspective_angle_fi)
        self.perspective_d_SpinBox.valueChanged.connect(
            self.render_area.sphere.set_perspective_d)
        self.perspective_ro_SpinBox.valueChanged.connect(
            self.render_area.sphere.set_perspective_ro)

        self.light_GroupBox.toggled.connect(lambda: self.render_area.set_light(
            self.light_GroupBox.isChecked(), self.clipping_CheckBox))
        self.clipping_CheckBox.stateChanged.connect(
            self.render_area.set_clipping)
        self.pen_color_Button.clicked.connect(
            lambda: self.render_area.set_pen_color(self.pen_color_Label))
        self.object_color_Button.clicked.connect(
            lambda: self.render_area.set_faces_color(self.object_color_Label))
        self.light_x_SpinBox.valueChanged.connect(
            self.render_area.sphere.set_light_x)
        self.light_y_SpinBox.valueChanged.connect(
            self.render_area.sphere.set_light_y)
        self.light_z_SpinBox.valueChanged.connect(
            self.render_area.sphere.set_light_z)

    def set_default_values(self):
        """
        Установка значений по умолчанию
        """
        self.render_area.sphere.set_approximation_step(
            self.approximation_step_SpinBox.value())
        self.render_area.sphere.set_radius(self.radius_SpinBox.value())
        self.render_area.sphere.set_x_rotate_angle(
            self.x_rotate_Slider.value())
        self.render_area.sphere.set_y_rotate_angle(
            self.y_rotate_Slider.value())
        self.render_area.sphere.set_z_rotate_angle(
            self.z_rotate_Slider.value())
        self.render_area.sphere.set_x_move(self.x_move_Slider.value())
        self.render_area.sphere.set_y_move(self.y_move_Slider.value())
        self.render_area.sphere.set_z_move(self.z_move_Slider.value())
        self.render_area.sphere.set_x_scale(self.x_scale_Slider.value())
        self.render_area.sphere.set_y_scale(self.y_scale_Slider.value())
        self.render_area.sphere.set_z_scale(self.z_scale_Slider.value())

        self.render_area.set_projection(self.default_projection)
        self.render_area.sphere.set_axonometric_angle_fi(
            self.axonometric_fi_angle_SpinBox.value())
        self.render_area.sphere.set_axonometric_angle_psi(
            self.axonometric_psi_angle_SpinBox.value())
        self.render_area.sphere.set_oblique_angle_alpha(
            self.oblique_alpha_angle_SpinBox.value())
        self.render_area.sphere.set_oblique_L(self.oblique_L_SpinBox.value())
        self.render_area.sphere.set_perspective_angle_teta(
            self.perspective_teta_angle_SpinBox.value())
        self.render_area.sphere.set_perspective_angle_fi(
            self.perspective_fi_angle_SpinBox.value())
        self.render_area.sphere.set_perspective_d(
            self.perspective_d_SpinBox.value())
        self.render_area.sphere.set_perspective_ro(
            self.perspective_ro_SpinBox.value())

        self.render_area.set_pen_width(self.pen_width_SpinBox.value())
        self.render_area.set_clipping(self.clipping_CheckBox.isChecked())
        self.render_area.sphere.set_light_x(self.light_x_SpinBox.value())
        self.render_area.sphere.set_light_y(self.light_y_SpinBox.value())
        self.render_area.sphere.set_light_z(self.light_z_SpinBox.value())

        self.light_GroupBox.setChecked(False)

    @staticmethod
    def create_slider(value, minimum, maximum, single_step, page_step,
                      tick_interval):
        """
        Создаёт и настраивает слайдер для формы
        :param value: Значение по умолчанию
        :param minimum: Минимально допустимое значение
        :param maximum: Максимально допустимое значение
        :param single_step: Шаг, с которым изменяется слайдер от нажатия на стрелки
        :param page_step: Шаг, с которым изменяется слайдер при нажатии PageUp и PageDown
        :param tick_interval: Интервал между метками под слайдером. Если 0, то будет выбран или single_step или page_step
        :return: QSlider
        """
        slider = QSlider(Qt.Horizontal)

        slider.setRange(minimum, maximum)
        slider.setSingleStep(single_step)
        slider.setPageStep(page_step)
        slider.setTickInterval(tick_interval)
        slider.setTickPosition(QSlider.TicksRight)
        slider.setValue(value)

        return slider

    @staticmethod
    def create_spinbox(value, minimum, maximum):
        """
        Создаёт и настраивает спинбокс для формы
        :param value: Значение по умолчанию
        :param minimum: Минимально допустимое значение
        :param maximum: Максимально допустимое значение
        :return: QSpinBox
        """
        spinbox = QSpinBox()

        spinbox.setRange(minimum, maximum)
        spinbox.setValue(value)

        return spinbox

    @staticmethod
    def create_double_spinbox(value, step, minimum, maximum):
        """
        Создаёт и настраивает спинбокс с дробными значениями для формы
        :param value: Значение по умолчанию
        :param step: Шаг изменения значения
        :param minimum: Минимально допустимое значение
        :param maximum: Максимально допустимое значение
        :return: QSpinBox
        """
        spinbox = QDoubleSpinBox()

        spinbox.setSingleStep(step)
        spinbox.setRange(minimum, maximum)
        spinbox.setValue(value)

        return spinbox
Beispiel #30
0
class Ui_Form(object):
    def __init__(self, obj):
        super().__init__()
        self.setupUi(obj)
        self.retranslateUi(obj)
        self.graphicsView = QGraphicsView(obj)
        self.graphicsView.setGeometry(QtCore.QRect(10, 10, 791, 441))
        self.graphicsView.setObjectName("graphicsView")
        self.scene = QtWidgets.QGraphicsScene()
        self.graphicsView.setScene(self.scene)

        pen = QtGui.QPen(QtCore.Qt.GlobalColor.gray)
        for i in range(-1 * self.graphicsView.height() // 2 + 10,
                       self.graphicsView.height() // 2 - 10):
            r1 = QtCore.QRectF(QtCore.QPointF(0, i), QtCore.QSizeF(1, 1))
            self.scene.addRect(r1, pen)

        for i in range(-1 * self.graphicsView.width() // 2 + 10,
                       self.graphicsView.width() // 2 - 10):
            r2 = QtCore.QRectF(QtCore.QPointF(i, 0), QtCore.QSizeF(1, 1))
            self.scene.addRect(r2, pen)

        self.coordsContainer = []
        self.centersContainer = []
        self.clastersContainer = []
        self.distance = None

    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(815, 678)

        self.startPushButton = QPushButton(Form)
        self.startPushButton.clicked.connect(
            self.startPushButton_button_clicked)
        self.startPushButton.setGeometry(QtCore.QRect(260, 620, 261, 41))
        self.startPushButton.setObjectName("startPushButton")

        self.coordsTextBox = QtWidgets.QPlainTextEdit(Form)
        self.coordsTextBox.setGeometry(QtCore.QRect(260, 470, 261, 81))
        self.coordsTextBox.setObjectName("coordsTextBox")

        self.CentersTextBox = QtWidgets.QPlainTextEdit(Form)
        self.CentersTextBox.setGeometry(QtCore.QRect(540, 470, 261, 81))
        self.CentersTextBox.setObjectName("CentersTextBox")

        self.addCordsPushButton = QPushButton(Form)
        self.addCordsPushButton.clicked.connect(
            self.addCordsPushButton_button_clicked)
        self.addCordsPushButton.setGeometry(QtCore.QRect(260, 570, 541, 31))
        self.addCordsPushButton.setObjectName("addCordsPushButton")

        self.groupBox = QtWidgets.QGroupBox(Form)
        self.groupBox.setGeometry(QtCore.QRect(10, 460, 241, 91))
        self.groupBox.setObjectName("groupBox")

        self.euclidRadioButton = QRadioButton(self.groupBox)
        self.euclidRadioButton.toggled.connect(self.euclidRadioButton_clicked)
        self.euclidRadioButton.setGeometry(QtCore.QRect(10, 20, 221, 31))
        self.euclidRadioButton.setObjectName("euclidRadioButton")

        self.chebishevRadioButton = QRadioButton(self.groupBox)
        self.chebishevRadioButton.toggled.connect(
            self.chebishevRadioButton_clicked)
        self.chebishevRadioButton.setGeometry(QtCore.QRect(10, 50, 221, 41))
        self.chebishevRadioButton.setObjectName("chebishevRadioButton")

        self.stepPushButton = QPushButton(Form)
        self.stepPushButton.clicked.connect(self.stepPushButton_button_clicked)
        self.stepPushButton.setGeometry(QtCore.QRect(540, 620, 261, 41))
        self.stepPushButton.setObjectName("stepPushButton")

        self.restartPushButton = QPushButton(Form)
        self.restartPushButton.clicked.connect(
            self.restartPushButton_button_clicked)
        self.restartPushButton.setGeometry(QtCore.QRect(10, 620, 241, 41))
        self.restartPushButton.setObjectName("restartPushButton")

        self.testPushButton = QPushButton(Form)
        self.testPushButton.clicked.connect(self.testPushButton_button_clicked)
        self.testPushButton.setGeometry(QtCore.QRect(10, 570, 241, 31))
        self.testPushButton.setObjectName("testPushButton")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.startPushButton.setText(_translate("Form", "START"))
        self.addCordsPushButton.setText(_translate("Form", "ADD COORDINATES"))
        self.groupBox.setTitle(_translate("Form", "Distance"))
        self.euclidRadioButton.setText(_translate("Form", "Euclid"))
        self.chebishevRadioButton.setText(_translate("Form", "Chebishev"))
        self.stepPushButton.setText(_translate("Form", "STEP"))
        self.restartPushButton.setText(_translate("Form", "RESTART"))
        self.testPushButton.setText(_translate("Form", "Set Test Dataset"))

    def drawLineToDot(self):
        pen = QtGui.QPen(QtCore.Qt.GlobalColor.blue)
        brush = QtGui.QBrush(QtCore.Qt.GlobalColor.blue)
        pen.setWidth(2)
        pen.setColor(QtCore.Qt.GlobalColor.blue)

        for i in range(len(self.clastersContainer)):
            for j in self.clastersContainer[i]:
                self.scene.addLine(
                    QtCore.QLineF(4 * j[0], -4 * j[1],
                                  4 * self.centersContainer[i][0],
                                  -4 * self.centersContainer[i][1]), pen)

    def stringParser(self, coords, centers):
        coords_l = None
        centers_l = None
        try:
            coords_string_array = coords.split(';')
            centers_string_array = centers.split(';')
            coords_l = []
            centers_l = []

            for i in coords_string_array:
                l = [float(k) for k in i.strip('()').split(',')]
                coords_l.append(l)

            for i in centers_string_array:
                l = [float(k) for k in i.strip('()').split(',')]
                centers_l.append(l)
        except:
            self.CentersTextBox.clear()
            self.coordsTextBox.clear()
            msg = QtWidgets.QMessageBox()
            msg.setIcon(QtWidgets.QMessageBox.Critical)
            msg.setText("Format Error")
            msg.setInformativeText('Follow the format!')
            msg.setWindowTitle("Error")
            msg.setStyleSheet("QLabel{font-size: 20px;}")
            msg.exec_()
            pass
        return coords_l, centers_l

    def add_coordinates_to_GraphView(self):
        pen = QtGui.QPen(QtCore.Qt.GlobalColor.black)
        brush = QtGui.QBrush(QtCore.Qt.GlobalColor.black)
        side = 4
        for i in self.coordsContainer:
            self.scene.addEllipse(i[0] * side - 3, -1 * i[1] * side - 3, 7, 7,
                                  pen, brush)

        pen = QtGui.QPen(QtCore.Qt.GlobalColor.red)
        brush = QtGui.QBrush(QtCore.Qt.GlobalColor.red)

        for i in self.centersContainer:
            self.scene.addEllipse(i[0] * side - 3, -1 * i[1] * side - 3, 7, 7,
                                  pen, brush)

    def addCordsPushButton_button_clicked(self):
        coordinates = self.coordsTextBox.toPlainText()
        centers = self.CentersTextBox.toPlainText()
        if coordinates == '' or centers == '':
            msg = QtWidgets.QMessageBox()
            msg.setIcon(QtWidgets.QMessageBox.Critical)
            msg.setText("Data Empty")
            msg.setInformativeText('Please, enter coords')
            msg.setWindowTitle("Error")
            msg.setStyleSheet("QLabel{font-size: 20px;}")
            msg.exec_()
            return

        coordinates_l, centers_l = self.stringParser(coordinates, centers)

        if coordinates_l is not None and centers_l is not None:
            co = self.coordsContainer.copy()
            ce = self.centersContainer.copy()

            co += coordinates_l.copy()
            ce += centers_l.copy()

            co.sort()
            ce.sort()

            co_new = list(num for num, _ in itertools.groupby(co))
            ce_new = list(num for num, _ in itertools.groupby(ce))

            self.centersContainer = ce_new.copy()
            self.coordsContainer = co_new.copy()

            print(self.centersContainer)
            print(self.coordsContainer)

            self.add_coordinates_to_GraphView()

    def startPushButton_button_clicked(self):
        if self.coordsContainer == [] or self.centersContainer == []:
            msg = QtWidgets.QMessageBox()
            msg.setIcon(QtWidgets.QMessageBox.Critical)
            msg.setText("Data Empty")
            msg.setInformativeText('Please, enter coords')
            msg.setWindowTitle("Error")
            msg.setStyleSheet("QLabel{font-size: 20px;}")
            msg.exec_()
            return
        self.chebishevRadioButton.setEnabled(False)
        self.euclidRadioButton.setEnabled(False)
        self.addCordsPushButton.setEnabled(False)
        self.coordsTextBox.setEnabled(False)
        self.CentersTextBox.setEnabled(False)
        self.startPushButton.setEnabled(False)
        self.testPushButton.setEnabled(False)

        if self.distance == 'E':

            for _ in range(len(self.centersContainer)):
                self.clastersContainer.append([])

            for i in self.coordsContainer:
                range_l = []
                for c in self.centersContainer:
                    range_l.append(
                        math.sqrt((i[0] - c[0])**2 + (i[1] - c[1])**2))

                minindex = range_l.index(min(range_l))
                self.clastersContainer[minindex].append(i)
            self.drawLineToDot()
        elif self.distance == 'H':
            for _ in range(len(self.centersContainer)):
                self.clastersContainer.append([])

            for i in self.coordsContainer:
                range_l = []
                for c in self.centersContainer:
                    range_l.append(max(abs(i[0] - c[0]), abs(i[1] - c[1])))

                minindex = range_l.index(min(range_l))
                self.clastersContainer[minindex].append(i)
            self.drawLineToDot()

    def stepPushButton_button_clicked(self):
        if self.centersContainer is None or self.coordsContainer is None:
            msg = QtWidgets.QMessageBox()
            msg.setIcon(QtWidgets.QMessageBox.Critical)
            msg.setText("Empty Error")
            msg.setInformativeText('Not enough dots!')
            msg.setWindowTitle("Error")
            msg.setStyleSheet("QLabel{font-size: 20px;}")
            msg.exec_()
            return

        claster_backup = self.clastersContainer.copy()
        new_centers = []
        for i in self.clastersContainer:
            new_x, new_y = 0, 0
            for k in i:
                new_x += k[0]
                new_y += k[1]
            new_x /= len(i)
            new_y /= len(i)
            new_centers.append([new_x, new_y])

        self.centersContainer = new_centers.copy()
        self.redrow(False)
        self.add_coordinates_to_GraphView()
        self.clastersContainer.clear()
        for _ in range(len(self.centersContainer)):
            self.clastersContainer.append([])

        for i in self.coordsContainer:
            range_l = []
            for c in new_centers:
                range_l.append(math.sqrt((i[0] - c[0])**2 + (i[1] - c[1])**2))

            minindex = range_l.index(min(range_l))
            self.clastersContainer[minindex].append(i)
        self.drawLineToDot()
        new_back_clasters = self.clastersContainer.copy()

        if claster_backup == new_back_clasters:
            self.stepPushButton.setEnabled(False)

    def redrow(self, full):
        self.scene.clear()
        pen = QtGui.QPen(QtCore.Qt.GlobalColor.gray)
        for i in range(-1 * self.graphicsView.height() // 2 + 10,
                       self.graphicsView.height() // 2 - 10):
            r1 = QtCore.QRectF(QtCore.QPointF(0, i), QtCore.QSizeF(1, 1))
            self.scene.addRect(r1, pen)

        for i in range(-1 * self.graphicsView.width() // 2 + 10,
                       self.graphicsView.width() // 2 - 10):
            r2 = QtCore.QRectF(QtCore.QPointF(i, 0), QtCore.QSizeF(1, 1))
            self.scene.addRect(r2, pen)
        if not full:

            pen2 = QtGui.QPen(QtCore.Qt.GlobalColor.black)
            brush2 = QtGui.QBrush(QtCore.Qt.GlobalColor.black)

            side = 4
            for i in self.coordsContainer:
                self.scene.addEllipse(i[0] * side - 3, -1 * i[1] * side - 3, 7,
                                      7, pen2, brush2)

    def restartPushButton_button_clicked(self):
        self.chebishevRadioButton.setEnabled(True)
        self.euclidRadioButton.setEnabled(True)
        self.addCordsPushButton.setEnabled(True)
        self.coordsTextBox.setEnabled(True)
        self.CentersTextBox.setEnabled(True)
        self.testPushButton.setEnabled(True)
        self.startPushButton.setEnabled(True)
        self.stepPushButton.setEnabled(True)
        self.redrow(True)

        self.coordsContainer.clear()
        self.centersContainer.clear()
        self.clastersContainer.clear()

    def testPushButton_button_clicked(self):
        self.coordsTextBox.setPlainText(TEST_COORDS)
        if self.distance == 'E':
            self.CentersTextBox.setPlainText(EUCLID_TEST_CENTERS)
        elif self.distance == 'H':
            self.CentersTextBox.setPlainText(CHEBISHEV_TEST_CENTERS)
        else:
            self.coordsTextBox.clear()
            msg = QtWidgets.QMessageBox()
            msg.setIcon(QtWidgets.QMessageBox.Critical)
            msg.setText("Distance not set")
            msg.setInformativeText('Please, pick the distance')
            msg.setWindowTitle("Error")
            msg.setStyleSheet("QLabel{font-size: 20px;}")
            msg.exec_()
            pass

    def euclidRadioButton_clicked(self):
        if self.euclidRadioButton.isChecked():
            self.distance = 'E'

    def chebishevRadioButton_clicked(self):
        if self.chebishevRadioButton.isChecked():
            self.distance = 'H'
Beispiel #31
0
class Ui_Dialog(object):
    def __init__(self, Dialog):
        super(Ui_Dialog, self).__init__()
        # ----- App Design ----- #
        # To make this to work in Fullscreen; set 'self.window_width' and 'self.window_height' to 'size.width()' and 'size.height()'
        # To make this to work in Fullscreen-Windowed; set 'self.window_width' and 'self.window_height' to 'rect.width()' and 'rect.height()'
        self.window_width = 500
        self.window_height = 800
        # self.window_width = size.width()    # Fullscreen
        # self.window_height = size.height()  # Fullscreen
        self.drop_down_width = self.window_width // 2 + 50
        self.notation_width = self.drop_down_width // 2
        self.widget_height = self.window_height // 20
        self.label_width = self.window_width // 4
        self.label_padding_left = self.window_width // 20
        self.content_padding_left = self.label_padding_left + self.label_width
        self.padding_top = self.window_height // 10
        self.v_space_between_widgets = self.window_height // 5

        self.app_font = QFont()
        self.output_text_font = QFont()
        self.app_font.setPointSize(
            (self.window_width + self.window_height) // 100)
        self.output_text_font.setPointSize(
            (self.window_width + self.window_height) // 120)

        self.label_style = 'color: rgb(176, 85, 87);'
        self.option_menu_style = 'color: rgb(158, 212, 124);'
        self.input_menu_style = 'color: rgb(15, 99, 189);'
        self.output_text_style = 'color: rgba(255, 255, 255, 150);'
        self.reset_button_style = '\
            background-color: red;\
            border-radius: 15px;\
            color: rgb(0, 0, 0);'

        # ----- App Window Settings ----- #
        Dialog.setObjectName("Dialog")
        self.set_window_resizable(window_obj=Dialog,
                                  width=self.window_width,
                                  height=self.window_height,
                                  flag=False)

        # ----- Widgets ----- #
        self.notation_label = QLabel(Dialog)
        self.notation_S = QRadioButton(Dialog)
        self.notation_b = QRadioButton(Dialog)
        self.option_label = QLabel(Dialog)
        self.option_menu = QComboBox(Dialog)
        self.input_label = QLabel(Dialog)
        self.input_menu = QComboBox(Dialog)
        self.output_label = QLabel(Dialog)
        self.output_text = QLineEdit(Dialog)
        self.reset_button = QPushButton(Dialog)
        self.va_button = QPushButton(Dialog)

        # ----- Music Logic ----- #
        music = Music()
        self.notesS = music.notesS
        self.notesb = music.notesb
        self.notes = self.notesS
        self.options_menu_vals = tuple()
        with open(features, 'r') as f:
            self.options_menu_vals = tuple([x.strip() for x in f.readlines()])
        self.input_menu_vals = tuple()
        self.rel_maj_min_options = ('Relative Major', 'Relative Minor')
        self.major_minor_options = ('Major', 'Minor')
        self.guitar_frets_options = tuple([str(i) for i in range(1, 23)
                                           ])  # For Capo position entry
        self.sub_menu_selected = dict()  # To Keep track of options selected
        self.select_data = '--Select--'
        self.option_change_detect = ''
        self.input_change_detect = ''

        # ----- Voice Assistant ----- #
        self.va = Voice_Assistant()

    def setupUi(self, Dialog):
        # Notations
        self.notation_label.setFont(self.app_font)
        self.notation_label.setGeometry(
            QtCore.QRect(self.label_padding_left, self.padding_top,
                         self.label_width, self.widget_height))
        self.notation_label.setObjectName("notation_label")
        self.notation_label.setStyleSheet(self.label_style)
        self.notation_S.setFont(self.app_font)
        self.notation_S.setGeometry(
            QtCore.QRect(self.content_padding_left, self.padding_top,
                         self.notation_width, self.widget_height))
        self.notation_S.setObjectName("notation_S")
        self.notation_S.setChecked(True)
        self.notation_b.setFont(self.app_font)
        self.notation_b.setGeometry(
            QtCore.QRect(self.content_padding_left + self.notation_width,
                         self.padding_top, self.notation_width,
                         self.widget_height))
        self.notation_b.setObjectName("notation_b")

        self.padding_top += self.v_space_between_widgets
        # Option Menu
        self.option_label.setFont(self.app_font)
        self.option_label.setGeometry(
            QtCore.QRect(self.label_padding_left, self.padding_top,
                         self.label_width, self.widget_height))
        self.option_label.setObjectName("options_label")
        self.option_label.setStyleSheet(self.label_style)
        self.option_menu.setFont(self.app_font)
        self.option_menu.setGeometry(
            QtCore.QRect(self.content_padding_left, self.padding_top - 2,
                         self.drop_down_width, self.widget_height))
        self.option_menu.setObjectName("option_menu")

        self.option_menu.addItem(self.select_data)
        self.option_menu.addItems(self.options_menu_vals)
        self.option_menu.currentIndexChanged.connect(
            self.option_selection_change)
        # self.option_menu.lineEdit().setAlignment(QtCore.Qt.AlignCenter)
        self.option_menu.setStyleSheet(self.option_menu_style)

        self.padding_top += self.v_space_between_widgets
        # Input Menu
        self.input_label.setFont(self.app_font)
        self.input_label.setGeometry(
            QtCore.QRect(self.label_padding_left, self.padding_top,
                         self.label_width, self.widget_height))
        self.input_label.setObjectName("input_label")
        self.input_label.setStyleSheet(self.label_style)
        self.input_menu.setFont(self.app_font)
        self.input_menu.setGeometry(
            QtCore.QRect(self.content_padding_left, self.padding_top - 2,
                         self.drop_down_width, self.widget_height))
        self.input_menu.setObjectName("input_menu")
        self.input_menu.setDisabled(True)
        self.input_menu.setStyleSheet(self.input_menu_style)

        self.padding_top += self.v_space_between_widgets
        # Output
        self.output_label.setFont(self.app_font)
        self.output_label.setGeometry(
            QtCore.QRect(self.label_padding_left, self.padding_top,
                         self.label_width, self.widget_height))
        self.output_label.setObjectName("output_label")
        self.output_label.setStyleSheet(self.label_style)
        self.output_text.setFont(self.output_text_font)
        self.output_text.setGeometry(
            QtCore.QRect(self.content_padding_left, self.padding_top - 2,
                         self.drop_down_width, self.widget_height))
        self.output_text.setObjectName("output_text")
        self.output_text.setDisabled(True)
        self.output_text.setStyleSheet(self.output_text_style)

        self.padding_top += self.v_space_between_widgets // 2
        # App RESET
        self.reset_button.setFont(self.app_font)
        self.reset_button.setGeometry(
            QtCore.QRect(self.label_padding_left, self.padding_top,
                         self.label_width + self.drop_down_width,
                         self.widget_height))
        self.reset_button.setObjectName("reset_button")
        self.reset_button.clicked.connect(self.reset)
        self.reset_button.setIcon(QtGui.QIcon(reset_icon))
        self.reset_button.setIconSize(
            QtCore.QSize(self.widget_height, self.widget_height))
        self.reset_button.setStyleSheet(self.reset_button_style)

        self.padding_top += self.v_space_between_widgets // 2
        # Voice Assitant
        self.va_button.setFont(self.app_font)
        self.va_button.setGeometry(
            QtCore.QRect(self.label_padding_left, self.padding_top,
                         self.label_width + self.drop_down_width,
                         self.widget_height))
        self.va_button.setObjectName("va_button")
        self.va_button.clicked.connect(self.Voice_Assistant_Call)
        self.va_button.setIcon(QtGui.QIcon(app_logo))
        self.va_button.setIconSize(
            QtCore.QSize(self.widget_height, self.widget_height))
        self.va_button.setStyleSheet(self.reset_button_style)

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def option_selection_change(self):
        selected_text = self.option_menu.currentText()

        # ----- Detect change in menu selection ----- #
        if self.option_change_detect != selected_text:
            print(self.sub_menu_selected)
            print('Option Menu Change Detected')
            # self.input_menu.clear()
            self.output_text.clear(
            )  # This is working; "input_menu.clear()" getting hanged
            self.input_menu.addItem(self.select_data)
            print('Input Menu cleared')
            self.option_change_detect = selected_text
            print('New opt change detect set')

        # ----- Change Input Menu Values ----- #
        if selected_text != self.select_data:
            print('Option Item Selected:', selected_text)
            self.input_menu.setDisabled(False)
            if selected_text == self.options_menu_vals[0]:  # Major Scale
                print('maj scale')
                if self.notation_S.isChecked():
                    self.notes = self.notesS
                elif self.notation_b.isChecked():
                    self.notes = self.notesb
                self.input_menu_vals = self.notes
            elif selected_text == self.options_menu_vals[1]:  # Major Chord
                print('maj chord')
                if self.notation_S.isChecked():
                    self.notes = self.notesS
                elif self.notation_b.isChecked():
                    self.notes = self.notesb
                self.input_menu_vals = self.notes
            elif selected_text == self.options_menu_vals[
                    2]:  # Chords in Major Scale
                print('chords in maj scale')
                if self.notation_S.isChecked():
                    self.notes = self.notesS
                elif self.notation_b.isChecked():
                    self.notes = self.notesb
                self.input_menu_vals = self.notes
            print('rcvd inp menu vals')
            self.input_menu.addItems(self.input_menu_vals)
            self.input_menu.currentIndexChanged.connect(
                self.input_selection_change)
            print('set inp menu vals')
        else:
            self.input_menu.clear()
            self.input_menu.setDisabled(True)

        # ----- To Keep track of Selections ----- #
        if self.option_menu.currentText(
        ) not in self.sub_menu_selected and self.option_menu.currentText(
        ) != self.select_data:
            self.sub_menu_selected[self.option_menu.currentText()] = []

    def input_selection_change(self):
        selected_text = self.input_menu.currentText()

        # ----- Detect change in menu selection ----- #
        if self.input_change_detect != selected_text:
            self.input_change_detect = selected_text

        # ----- Action performed on Input Menu Values ----- #
        if selected_text != self.select_data:
            option_menu_selected_text = self.option_menu.currentText()
            if option_menu_selected_text == self.options_menu_vals[
                    0]:  # Major Scale
                note = selected_text
                music = Music(note)
                result = music.major_scale()
                self.output_text.setText('     '.join(result))
            elif option_menu_selected_text == self.options_menu_vals[
                    1]:  # Major Chord
                note = selected_text
                music = Music(note)
                result = music.major_chord()
                self.output_text.setText('     '.join(result))
            elif option_menu_selected_text == self.options_menu_vals[
                    2]:  # Chords in Major Scale
                note = selected_text
                music = Music(note)
                result = music.chords_in_major_scale()
                self.output_text.setText('     '.join(result))

        # ----- To Keep track of Selections ----- #
        if self.option_menu.currentText() != self.select_data:
            if self.option_menu.currentText() in self.sub_menu_selected:
                self.sub_menu_selected[self.option_menu.currentText()].append(
                    selected_text)
                self.sub_menu_selected[self.option_menu.currentText()] = list(
                    set(self.sub_menu_selected[
                        self.option_menu.currentText()]))
            else:
                self.sub_menu_selected[self.option_menu.currentText()] = list(
                    set([selected_text]))

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Music Theory Guide"))
        self.notation_label.setText(_translate("Dialog", "Notation"))
        self.notation_S.setIcon(QtGui.QIcon(sharp_icon))
        self.notation_b.setIcon(QtGui.QIcon(flat_icon))
        self.option_label.setText(_translate("Dialog", "Options"))
        self.input_label.setText(_translate("Dialog", "Input"))
        self.output_label.setText(_translate("Dialog", "Output"))
        self.output_text.setText(_translate("Dialog", ""))
        self.reset_button.setText(_translate("Dialog", "Reset Application"))
        self.va_button.setText(_translate("Dialog", "Voice Assistant"))

    def set_window_resizable(self, window_obj, width, height, flag=False):
        if not flag:
            window_obj.setGeometry(rect.width() // 2 - width // 2,
                                   rect.height() // 2 - height // 2, width,
                                   height)
            window_obj.setMaximumHeight(height)
            window_obj.setMinimumHeight(height)
            window_obj.setMaximumWidth(width)
            window_obj.setMinimumWidth(width)
        else:
            window_obj.resize(width, height)

    def reset(self):
        self.notation_S.setChecked(True)
        self.option_menu.setCurrentIndex(0)
        self.input_menu.clear()
        self.output_text.setText('')

    def Voice_Assistant_Call(self):
        self.va.start_AI_engine()
Beispiel #32
0
class FormWidget(QWidget):
    def __init__(self, parent):
        super(FormWidget, self).__init__(parent)
        #水平佈局
        self.Hlayout_1 = QHBoxLayout()
        self.Hlayout_2 = QHBoxLayout()
        self.Hlayout_3 = QHBoxLayout()
        #垂直佈局
        self.Vlayout_1 = QVBoxLayout()
        self.Vlayout_2 = QVBoxLayout()
        self.Vlayout_3 = QVBoxLayout()

        #實例化標籤與列表模組
        self.styleLabel_1 = QLabel('Set Style')
        self.styleComboBox = QComboBox()

        #從QStyleFactory中增加多個顯示樣式到列表模組
        self.styleComboBox.addItems(QStyleFactory.keys())

        #選擇當前視窗的風格
        index = self.styleComboBox.findText(QApplication.style().objectName(),
                                            Qt.MatchFixedString)

        #設置當前視窗的風格
        self.styleComboBox.setCurrentIndex(index)

        #通過combobox模組選擇視窗風格
        self.styleComboBox.activated[str].connect(self.handlestyleChanged)

        self.progress = QProgressBar(self)
        self.progress.setGeometry(0, 0, 10, 10)

        # QRadioButton
        self.styleLabel_2 = QLabel('Set Style')
        # self.styleLabel_2.setAlignment(Qt.AlignCenter)

        self.macintosh = QRadioButton(self)
        self.macintosh.setObjectName("macintosh")
        self.macintosh.setText("macintosh")
        self.windows = QRadioButton(self)
        self.windows.setObjectName("windows")
        self.windows.setText("windows")
        self.fusion = QRadioButton(self)
        self.fusion.setObjectName("fusion")
        self.fusion.setText("fusion")

        # 設定選擇字體
        self.btn_fontChoice = QPushButton(QIcon("typography.png"),
                                          "Font Style", self)
        self.btn_fontChoice.setShortcut("Ctrl+F")
        self.btn_fontChoice.clicked.connect(self.fontChoice)

        # Add a button shortcut
        self.btn_download = QPushButton("Download", self)
        self.btn_download.setShortcut("Meta+D")
        # self.btn_download.resize(200,60)
        # self.btn_download.move(150,135)
        self.btn_download.clicked.connect(self.download)

        # 空間排版物件
        spacerItem1 = QSpacerItem(0, 0, QSizePolicy.Expanding,
                                  QSizePolicy.Expanding)
        #QSizePolicy
        # - Fixed
        # - Minimum
        # - Maximum
        # - Preferred
        # - MinimumExpanding
        # - Expanding
        # - Ignored

        # 開始增加模組到主視窗,設置視窗佈置
        # 將視窗設定水平佈置
        self.setLayout(self.Hlayout_1)

        # 將Hlayout_1分為三份
        self.Hlayout_1.addLayout(self.Vlayout_1)
        self.Hlayout_1.addLayout(self.Vlayout_2)
        self.Hlayout_1.addLayout(self.Vlayout_3)

        # 在最左側的Vlayout_1加入QRadioButton
        self.Vlayout_1.addWidget(self.styleLabel_2)
        self.Vlayout_1.addWidget(self.macintosh)
        self.Vlayout_1.addWidget(self.windows)
        self.Vlayout_1.addWidget(self.fusion)
        # 在最左側的Vlayout_1加入spacerItem
        self.Vlayout_1.addItem(spacerItem1)
        self.Vlayout_1.addWidget(self.btn_fontChoice)

        # 在中間的Vlayout_2加入兩個水平佈置與一個spacerItem
        self.Vlayout_2.addLayout(self.Hlayout_2)
        self.Vlayout_2.addLayout(self.Hlayout_3)
        self.Vlayout_2.addItem(spacerItem1)

        # 在中間Vlayout_2最上方Hlayout_2左側加入文字標籤
        self.Hlayout_2.addWidget(self.styleLabel_1)
        # 在中間Vlayout_2最上方Hlayout_2右側加入ComboBox
        self.Hlayout_2.addWidget(self.styleComboBox)

        # 在中間Vlayout_2最下方Hlayout_3左側加入progressBar
        self.Hlayout_3.addWidget(self.progress)
        # 在中間Vlayout_2最下方Hlayout_3右側加入按鈕
        self.Hlayout_3.addWidget(self.btn_download)

        # 在最右側的Vlayout_3加入spacerItem
        self.Vlayout_3.addItem(spacerItem1)

    def fontChoice(self):
        font, valid = QFontDialog.getFont()
        if valid:
            self.styleLabel_1.setFont(font)
            self.styleLabel_2.setFont(font)
            self.styleComboBox.setFont(font)

    #改變視窗風格
    def handlestyleChanged(self, style):
        QApplication.setStyle(style)
        print(QApplication.style().objectName(), Qt.MatchFixedString)

    def download(self):
        self.completed = 0
        while self.completed < 100:
            self.completed += 0.1
            self.progress.setValue(self.completed)

    def downloadCompleted(self):
        completedNotice = QMessageBox.information(self, "completed",
                                                  "Completed!")
Beispiel #33
0
def fill_widget(name, widget):
    if name == "atom":
        layout = QVBoxLayout()
        layout.setContentsMargins(0,0,0,5)
        layout.setSpacing(0)
        widget.setLayout(layout)
        layout.addWidget(QLabel("Place helium atom at:"), alignment=Qt.AlignCenter)
        button_area = QWidget()
        layout.addWidget(button_area, alignment=Qt.AlignCenter)
        button_layout = QGridLayout()
        button_area.setLayout(button_layout)
        button = QRadioButton("Center of view")
        button.setChecked(True)
        button.setObjectName("atom centered")
        button_layout.addWidget(button, 0, 0, 1, 7, alignment=Qt.AlignLeft)
        button_layout.addWidget(QRadioButton(""), 1, 0, alignment=Qt.AlignLeft)
        for i, axis in enumerate("xyz"):
            button_layout.addWidget(QLabel(axis + ":"), 1, i*2+1, alignment=Qt.AlignRight)
            coord_entry = QLineEdit()
            coord_entry.setText("0")
            coord_entry.setFixedWidth(50)
            coord_entry.setValidator(QDoubleValidator())
            coord_entry.setObjectName(axis + " coord")
            button_layout.addWidget(coord_entry, 1, 2*(i+1), alignment=Qt.AlignLeft)
        tip = QLabel("Use 'Modify Structure' section to change element type and add bonded atoms")
        tip.setWordWrap(True)
        # specify alignment within the label itself (instead of the layout) so that the label
        # is given the full width of the layout to work with, otherwise you get unneeded line
        # wrapping
        tip.setAlignment(Qt.AlignCenter)
        layout.addWidget(tip)
        res_name_area = QWidget()
        layout.addWidget(res_name_area, alignment=Qt.AlignCenter)
        res_name_layout = QHBoxLayout()
        res_name_area.setLayout(res_name_layout)
        res_name_layout.addWidget(QLabel("Residue name:"))
        res_name_entry = QLineEdit()
        res_name_entry.setText("UNL")
        res_name_entry.setFixedWidth(50)
        res_name_entry.setObjectName("res name")
        res_name_layout.addWidget(res_name_entry)
        check_box = QCheckBox("Select placed atom")
        check_box.setChecked(True)
        check_box.setObjectName("select atom")
        layout.addWidget(check_box, alignment=Qt.AlignCenter)
        layout.addStretch(1)
    elif name == "peptide":
        layout = QVBoxLayout()
        layout.setContentsMargins(3,0,3,5)
        layout.setSpacing(0)
        widget.setLayout(layout)
        layout.addWidget(QLabel("Peptide Sequence", alignment=Qt.AlignCenter))
        peptide_seq = QTextEdit()
        peptide_seq.setObjectName("peptide sequence")
        layout.addWidget(peptide_seq, stretch=1)
        tip = QLabel("'Apply' button will bring up dialog for setting"
            "\N{GREEK CAPITAL LETTER PHI}/\N{GREEK CAPITAL LETTER PSI} angles")
        tip.setWordWrap(True)
        # specify alignment within the label itself (instead of the layout) so that the label
        # is given the full width of the layout to work with, otherwise you get unneeded line
        # wrapping
        tip.setAlignment(Qt.AlignCenter)
        layout.addWidget(tip)
Beispiel #34
0
class Ui_MainWindow(object):
    def Assistent(self):
        print('jsdj')
        self.speak("Hi Divanshu, what can I do for you?")
        # while 1:
        data = self.recordAudio()
        self.jarvis(data)

    def speak(self, audioString):
        print(audioString)
        tts = gTTS(text=audioString, lang='en')
        filename = 'temp.mp3'
        tts.save(filename)

        music = pyglet.media.load(filename, streaming=False)
        music.play()

        time.sleep(music.duration)
        os.remove(filename)

    def recordAudio(self):
        print('igudczx')
        r = sr.Recognizer()
        with sr.Microphone() as source:
            print("Say something!")
            audio = r.listen(source)
        #
        data = "how are you"
        # try:
        #     data = r.recognize_google(audio)
        #     print("You said: " + data)
        # except sr.UnknownValueError:
        #     print("Google Speech Recognition could not understand audio")
        # except sr.RequestError as e:
        #     print("Could not request results from Google Speech Recognition service; {0}".format(e))
        #
        return data

    def jarvis(self, data):
        print('xcgyu')
        if "how are you" in data:
            self.speak("I am fine")

        if "what time is it" in data:
            self.speak(ctime())

        if "where is" in data:
            ##        data = data.split(" ")
            location = data[9:]
            self.speak("Hold on Divanshu, I will show you where " + location +
                       " is.")
            ##        os.system("chromium-browser https://www.google.nl/maps/place/" + location + "/&amp;")
            webbrowser.open("https://www.google.nl/maps/place/" + location +
                            "/&amp;",
                            new=new)
        if "open" in data:
            ##        data = data.split(" ")
            location = data[5:]
            self.speak("Hold on Divanshu")
            webbrowser.open("https://www." + location + ".com", new=new)
        if "search for" in data:
            data = data[10:]
            self.speak("give me some time")
            webbrowser.open(
                "https://www.google.com/search?source=hp&ei=ch0FWr-lLsP5kwWiiYugBw&q="
                + data + "&oq=" + data +
                "&gs_l=psy-ab.3..0i131k1l3j0i20i264k1l2j0i131k1j0l2j0i131k1l2.12371.14491.0.14839.10.9.0.0.0.0.572.1086.2-2j5-1.4.0....0...1.1.64.psy-ab..6.4.1404.6..35i39k1.319.-lYZLuRyYno",
                new=new)
        if "play" and "on YouTube" in data:
            data = data[5:][::-1][11:][::-1]
            self.speak("playing")
            webbrowser.open("https://www.youtube.com/results?search_query=" +
                            data,
                            new=new)

        if "give me direction" in data:
            self.speak("what is your location")
            text1 = self.recordAudio()
            self.speak("where you want to go")
            text2 = self.recordAudio()
            webbrowser.open("https://www.google.com/maps/dir/" + text1 + "/" +
                            text2 + "/")

        if "top" and "headline" and "Hindu" in data:
            link = 'http://www.thehindu.com/todays-paper/'
            r = requests.get(link)
            soup = BeautifulSoup(r.content, "html.parser")

            c = 0
            for i in soup.find_all("ul", {'class': 'archive-list'}):
                for j in i.find_all("li"):
                    k = j.text
                    if c <= 15 and k != 'nearby':
                        self.speak(k)
                        c += 1

        if "top" and "headline" and "times of India" in data:
            link = 'https://timesofindia.indiatimes.com/mostread.cms?day=1'
            r = requests.get(link)
            soup = BeautifulSoup(r.content, "html.parser")
            c = 0

            for i in soup.find_all("div", {'class': 'listing4 clearfix'}):
                for j in i.find_all("li"):
                    k = j.text
                    if c <= 10:
                        self.speak(k)
                        c += 1

        if "launch" in data:
            data = data[7:]
            try:
                os.startfile('E:\\python files\\speech to text\\exe files\\' +
                             data)
            except:
                print("check again")

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(460, 247)
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.horizontalLayout = QHBoxLayout(self.centralwidget)
        self.horizontalLayout.setObjectName("horizontalLayout")

        ##################################### Radio Button 1 #####################################################

        self.radioButton = QRadioButton(self.centralwidget)
        self.radioButton.setObjectName("radioButton")
        self.radioButton.clicked.connect(self.Assistent)
        self.horizontalLayout.addWidget(self.radioButton)

        #################################### Radio Button 1 #####################################################

        self.radioButton_2 = QRadioButton(self.centralwidget)
        self.radioButton_2.setObjectName("radioButton_2")
        # self.radioButton_2.clicked.connect()
        self.horizontalLayout.addWidget(self.radioButton_2)

        ############################################################################################################

        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.radioButton.setText(_translate("MainWindow", "start "))
        self.radioButton_2.setText(_translate("MainWindow", "off"))
Beispiel #35
0
class UiFacebook(PageWindow):  # Facebook UI
    def __init__(self):
        super().__init__()
        self.initUI()
        self.setWindowTitle("FaceBook - ELITELOADER")

    def initUI(self):
        self.setupUi(self)

    def Progressbar_Manager(self, current, total, width):
        pct = (current / total) * 100
        self.progressBar.setValue(int(pct))

    def Download_H(self):  # For High Quality
        ERASE_LINE = '\x1b[2K'
        Location = os_path.join(data.get('loc'))
        try:
            html = requests.get(data.get('url'))
            hdvideo_url = search('hd_src:"(.+?)"', html.text)[1]
        except requests.ConnectionError as e:
            print("OOPS!! Connection Error.")
            return 'Connection Error\n' + 'Check your Internet'
        except requests.Timeout as e:
            print("OOPS!! Timeout Error")
            return 'Network Timeout'
        except requests.RequestException as e:
            print("OOPS!! General Error or Invalid URL")
            return 'General Error or Invalid URL'
        except (KeyboardInterrupt, SystemExit):
            print("Ok ok, quitting")
            exit(1)
        except TypeError:
            print("Video May be Private or Hd version not available")
            return 'Video May Private or Hd version not available'
        else:
            hd_url = hdvideo_url.replace('hd_src:"', '')
            print("\n")
            print("High Quality: " + hd_url)
            print("[+] Video Started Downloading")
            wget.download(hd_url, Location, bar=self.Progressbar_Manager)
            stdout.write(ERASE_LINE)
            print("\n")
            print("Video downloaded")
            return 'Video Downloaded Successfully !!'

    def Download_L(self):  # For Low Quality
        ERASE_LINE = '\x1b[2K'
        Location = os_path.join(data.get('loc'))
        try:
            html = requests.get(data.get('url'))
            sdvideo_url = search('sd_src:"(.+?)"', html.text)[1]
        except requests.ConnectionError as e:
            print("OOPS!! Connection Error.")
            return 'Connection Error\n' + 'Check your Internet'
        except requests.Timeout as e:
            print("OOPS!! Timeout Error")
            return 'Network Timeout'
        except requests.RequestException as e:
            print("OOPS!! General Error or Invalid URL")
            return 'General Error or Invalid URL'
        except (KeyboardInterrupt, SystemExit):
            print("Ok ok, quitting")
            exit(1)
        except TypeError:
            print("Video May Private or Invalid URL")
            return 'Video May be Private or Invalid URL'
        else:
            sd_url = sdvideo_url.replace('sd_src:"', '')
            print("\n")
            print("Normal Quality: " + sd_url)
            print("[+] Video Started Downloading")
            wget.download(sd_url, Location, bar=self.Progressbar_Manager)
            stdout.write(ERASE_LINE)
            print("\n")
            print("Video downloaded")
            return 'Video Downloaded Successfully !!'

    def Selector(self):
        """ Identifies which Quality is reqd."""
        if self.HighQual_radioButton.isChecked():
            print('HQ selected--fwding to manager')
            self.groupBox_forQuality.setVisible(False)
            self.pushButton.setVisible(False)
            self.label.setText('PLEASE WAIT..\nSTARTING DOWNLOAD...')
            sgs = QFileDialog.getExistingDirectory()
            print(sgs)
            data.add('loc', sgs)
            self.progressBar.setVisible(True)
            print(data)
            msg = self.Download_H()
            QMessageBox.question(self, 'ELITE', msg, QMessageBox.Ok)
            exit(0)

        if self.LowQual_radioButton.isChecked():
            print('LQ selected--fwding to manager')
            self.groupBox_forQuality.setVisible(False)
            self.pushButton.setVisible(False)
            self.label.setText('PLEASE WAIT..\nSTARTING DOWNLOAD...')
            sgs = QFileDialog.getExistingDirectory()
            print(sgs)
            data.add('loc', sgs)
            self.progressBar.setVisible(True)
            print(data)
            msg = self.Download_L()
            QMessageBox.question(self, 'ELITE', msg, QMessageBox.Ok)
            exit(0)

    def setupUi(self, facebook_dwn):
        facebook_dwn.setObjectName("facebook_dwn")
        facebook_dwn.resize(586, 379)
        self.centralwidget = QWidget(facebook_dwn)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QLabel(self.centralwidget)
        self.label.setGeometry(QRect(220, 10, 250, 61))
        font = QFont()
        font.setPointSize(14)
        font.setBold(True)
        font.setItalic(True)
        font.setWeight(75)
        self.label.setFont(font)
        self.label.setObjectName("Title_label")
        self.pushButton = QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QRect(460, 290, 88, 33))
        self.pushButton.setObjectName("pushButton")
        self.pushButton.clicked.connect(lambda: self.Selector())
        self.groupBox_forQuality = QGroupBox(self.centralwidget)
        self.groupBox_forQuality.setGeometry(QRect(200, 90, 141, 111))
        self.groupBox_forQuality.setObjectName("groupBox_for_videoFormats")
        self.HighQual_radioButton = QRadioButton(self.groupBox_forQuality)
        self.HighQual_radioButton.setGeometry(QRect(20, 30, 104, 23))
        self.HighQual_radioButton.setObjectName("mp4_radioButton")
        self.LowQual_radioButton = QRadioButton(self.groupBox_forQuality)
        self.LowQual_radioButton.setGeometry(QRect(20, 60, 104, 23))
        self.LowQual_radioButton.setObjectName("webm_radioButton")
        self.progressBar = QProgressBar(self.centralwidget)
        self.progressBar.setGeometry(QRect(110, 180, 391, 23))
        self.progressBar.setProperty("value", 0)
        self.progressBar.setObjectName("progressBar")
        self.progressBar.setVisible(False)
        facebook_dwn.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(facebook_dwn)
        self.menubar.setGeometry(QRect(0, 0, 586, 25))
        self.menubar.setObjectName("menubar")
        facebook_dwn.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(facebook_dwn)
        self.statusbar.setObjectName("statusbar")
        facebook_dwn.setStatusBar(self.statusbar)

        self.retranslateUi(facebook_dwn)
        QMetaObject.connectSlotsByName(facebook_dwn)

    def retranslateUi(self, facebook_dwn):
        _translate = QCoreApplication.translate
        facebook_dwn.setWindowTitle(
            _translate("facebook_dwn", "Facebook Video Download-ELITELOADER"))
        self.label.setText(_translate("facebook_dwn", "Select  Quality"))
        self.pushButton.setText(_translate("facebook_dwn", "Proceed"))
        self.groupBox_forQuality.setTitle(_translate("facebook_dwn",
                                                     "Quality"))
        self.HighQual_radioButton.setText(
            _translate("facebook_dwn", "High Quality"))
        self.LowQual_radioButton.setText(
            _translate("facebook_dwn", "Low Quality"))