Ejemplo n.º 1
0
    def initUI(self):
        self.setWindowTitle("查看回收站文件夹内容")
        self.form = QVBoxLayout()
        for item in iter(self.files):
            ico = QPushButton(set_file_icon(item.name), item.name)
            ico.setStyleSheet(
                "QPushButton {border:none; background:transparent; color:black;}"
            )
            ico.adjustSize()
            it = QLabel(f"<font color='#CCCCCC'>({item.size})</font>")
            hbox = QHBoxLayout()
            hbox.addWidget(ico)
            hbox.addStretch(1)
            hbox.addWidget(it)
            self.form.addLayout(hbox)

        self.form.setSpacing(10)
        self.buttonBox = QDialogButtonBox()
        self.buttonBox.setOrientation(Qt.Orientation.Horizontal)
        self.buttonBox.setStandardButtons(
            QDialogButtonBox.StandardButton.Close)
        self.buttonBox.button(
            QDialogButtonBox.StandardButton.Close).setText("关闭")
        self.buttonBox.setStyleSheet(btn_style)
        self.buttonBox.rejected.connect(self.reject)

        vbox = QVBoxLayout()
        vbox.addLayout(self.form)
        vbox.addStretch(1)
        vbox.addWidget(self.buttonBox)
        self.setLayout(vbox)
Ejemplo n.º 2
0
def delete_confirmation(parent, _id: str, action: Callable):
    msg = QMessageBox()
    msg.setText("Are you sure, you want to remove ?")
    msg.setStyleSheet('''
        background-color: #1d251c;
        color: #bdc0bd;
    ''')
    msg.setParent(parent)
    msg.setWindowModality(Qt.WindowModality.WindowModal)

    style = '''
    margin-top: 20px;
    border: none;
    '''
    yes_btn = QPushButton("  Yes")
    yes_btn.setIcon(QIcon(full_path("assets/images/icons/trash-can.ico")))
    yes_btn.setStyleSheet(style)

    no_btn = QPushButton("  Cancel")
    no_btn.setStyleSheet(style)
    no_btn.setIcon(QIcon(full_path("assets/images/icons/cancel.ico")))

    yes_btn.setDefault(True)

    msg.addButton(no_btn, msg.ButtonRole.NoRole)
    msg.addButton(yes_btn, msg.ButtonRole.YesRole)

    msg.buttonClicked.connect(lambda x: action(_id) if x.text().lower().strip() == "yes" else do_nothing())
    msg.exec()
class SettingsDialog(QDialog):
    def __init__(self):
        """ Dialog to manage the settings of the application """
        super().__init__()
        self.setWindowTitle("Settings")
        self.setFixedSize(310, 250)

        # Create the general settings widgets for managing the text color,
        # text alignment, and author of the app's content
        # NOTE: Altering the default CSS attributes, such as the color, of a
        # widget can change its appearance. Hence, the button may appear
        # rectangular depending upon your platform
        self.text_color_button = QPushButton()
        self.text_color_button.setStyleSheet(
            "background-color: #000000")  # Black
        self.text_color_button.clicked.connect(self.selectTextColor)

        self.align_left = QRadioButton(text="Left")  # Default
        self.align_left.setChecked(True)
        self.align_center = QRadioButton(text="Center")
        self.align_center.setChecked(False)
        self.align_right = QRadioButton(text="Right")
        self.align_right.setChecked(False)

        # Layout and container for alignment radio buttons
        align_v_box = QVBoxLayout()
        align_v_box.setContentsMargins(0, 5, 0, 0)
        align_v_box.addWidget(self.align_left)
        align_v_box.addWidget(self.align_center)
        align_v_box.addWidget(self.align_right)

        align_frame = QFrame()
        align_frame.setFrameShape(QFrame.Shape.NoFrame)
        align_frame.setLayout(align_v_box)

        self.author_name = QLineEdit()
        self.author_name.setMinimumWidth(160)

        self.button_box = QDialogButtonBox(
            QDialogButtonBox.StandardButtons.Ok
            | QDialogButtonBox.StandardButtons.Cancel)
        self.button_box.accepted.connect(self.accept)
        self.button_box.rejected.connect(self.reject)

        dialog_layout = QFormLayout()
        dialog_layout.addRow("<b>Text Color:</b>", self.text_color_button)
        dialog_layout.addRow(HorizontalSeparator())
        dialog_layout.addRow("<b>Text Alignment:</b>", align_frame)
        dialog_layout.addRow(HorizontalSeparator())
        dialog_layout.addRow("<b>Author:</b>", self.author_name)
        dialog_layout.addWidget(self.button_box)
        self.setLayout(dialog_layout)

    def selectTextColor(self):
        """Change the background color of the QPushButton to reflect the
        selected color. This is used to set the text color of the main window's QLineEdit."""
        color = QColorDialog.getColor()  # Returns QColor object
        # Use color.name() to get the color in the format "#RRGGBB"
        self.text_color_button.setStyleSheet(
            f"background-color: {color.name()}")
Ejemplo n.º 4
0
 def __init__(self, parent=None):
     super(WinForm, self).__init__(parent)
     self.setGeometry(300, 300, 350, 350)
     self.setWindowTitle('点击按钮关闭窗口')
     quit = QPushButton('Close', self)
     quit.setGeometry(10, 10, 60, 35)
     quit.setStyleSheet("background-color: red")
     quit.clicked.connect(self.close)
class MainWidget(QWidget):
    def __init__(self):
        super(MainWidget, self).__init__()
        self.resize(500, 600)
        self.setWindowTitle("喜马拉雅下载 by[Zero] " + __VERSION__)
        self.mainlayout = QVBoxLayout()
        self.setLayout(self.mainlayout)
        self.groupbox = QGroupBox("选择类型")
        self.groupbox.setFixedHeight(50)
        hlayout = QHBoxLayout(self.groupbox)
        self.signal_m4a = QRadioButton("单个下载")
        self.mut_m4a = QRadioButton("专辑下载")
        self.vip_signal_m4a = QRadioButton("VIP单个下载")
        self.vip_m4a = QRadioButton("VIP专辑下载")

        hlayout.addWidget(self.signal_m4a)
        hlayout.addWidget(self.mut_m4a)
        hlayout.addWidget(self.vip_signal_m4a)
        hlayout.addWidget(self.vip_m4a)
        self.mainlayout.addWidget(self.groupbox)

        frame01 = QFrame(self)
        child_layout = QVBoxLayout()
        print(self.width())
        label01 = QLabel("链   接", self)
        label02 = QLabel("下载目录", self)
        self.url_lineedit = QLineEdit(self)
        self.dir_lineedit = QLineEdit(self)
        hlayout01 = QHBoxLayout()
        hlayout01.addWidget(label01, 1)
        hlayout01.addWidget(self.url_lineedit, 9)
        hlayout02 = QHBoxLayout()
        hlayout02.addWidget(label02, 1)
        hlayout02.addWidget(self.dir_lineedit, 9)
        child_layout.addLayout(hlayout01)
        child_layout.addLayout(hlayout02)
        child_layout.setContentsMargins(
            5, 0, 5, 0)  #(int left, int top, int right, int bottom)
        frame01.setLayout(child_layout)
        self.download_progressbar = QProgressBar()
        self.download_progressbar.setAlignment(
            QtCore.Qt.Alignment.AlignCenter)  #文字居中
        self.download_progressbar.setValue(88)
        self.download_btn = QPushButton("开始下载")
        self.show_plaintextedit = QPlainTextEdit()
        self.show_plaintextedit.setMinimumHeight(400)
        self.mainlayout.addWidget(frame01)
        self.mainlayout.addWidget(self.download_progressbar)
        self.mainlayout.addWidget(self.download_btn)
        self.mainlayout.addWidget(self.show_plaintextedit)
        self.mainlayout.addStretch()
        ### 设置stylesheet
        self.download_btn.setStyleSheet(
            'QPushButton:pressed{ text-align: center;background-color:red;}')
Ejemplo n.º 6
0
class CreatePatientDialog(QDialog):
    def __init__(self, classification, patient, infoLabel, parent=None):
        super(CreatePatientDialog, self).__init__(parent)
        self.setWindowTitle('Create new patient')
        layout = QVBoxLayout()
        self.setLayout(layout)
        self.setMinimumWidth(200)

        self.patient = patient
        self.classifyExercises = classification
        self.infoLabel = infoLabel

        self.subjectEdit = QLineEdit()
        self.subjectEdit.setFixedHeight(30)
        self.subjectEdit.setText('Jozsika')
        self.subjectEdit.setStyleSheet(CustomQStyles.lineEditStyle)

        self.ageEdit = QLineEdit()
        self.ageEdit.setFixedHeight(30)
        self.ageEdit.setValidator(QIntValidator())
        self.ageEdit.setText('5')
        self.ageEdit.setStyleSheet(CustomQStyles.lineEditStyle)

        self.subjectButton = QPushButton('Add patient')
        self.subjectButton.setFixedHeight(30)
        self.subjectButton.setStyleSheet(CustomQStyles.outlineButtonStyle)
        self.subjectButton.clicked.connect(self.onSubjectSelected)
        self.subjectButton.setContentsMargins(5, 15, 5, 5)
        formContainer = QWidget()
        self.formLayout = QFormLayout()
        self.formLayout.addRow('Name', self.subjectEdit)
        self.formLayout.addRow('Age', self.ageEdit)
        self.formLayout.addWidget(self.subjectButton)
        self.formLayout.setFormAlignment(Qt.Alignment.AlignCenter)
        formContainer.setLayout(self.formLayout)
        formContainer.setStyleSheet(
            "background-color: white; border-radius: 7px;")
        layout.addWidget(formContainer)

    def onSubjectSelected(self):
        if self.classifyExercises is not None \
                and "" != self.subjectEdit.text() \
                and "" != self.ageEdit.text():
            self.subject = self.subjectEdit.text()
            self.classifyExercises.subject = self.subject
            self.classifyExercises.age = self.ageEdit.text()
            self.infoLabel.setText("Subject name set to " + self.subject +
                                   ", age " + self.classifyExercises.age)
            self.close()
Ejemplo n.º 7
0
 def createRow(self, exercise, index):
     item = QHBoxLayout()
     label = QLabel(exercise.name)
     item.addWidget(label)
     item.setAlignment(label, Qt.Alignment.AlignCenter)
     button = QPushButton(exercise.assigned_key[0])
     # button.installEventFilter(self)
     button.setStyleSheet(""" QPushButton
         {
             border: 1px solid grey;
             background-color: white;
         }
         """)
     button.clicked.connect(partial(self.openDialog, button))
     self.buttons.append(button)
     item.addWidget(button)
     self.mainLayout.addLayout(item, index, 0)
     print(index, exercise.name, exercise.assigned_key)
Ejemplo n.º 8
0
    def exerciseLayout(self, index):
        hLayout = QHBoxLayout()
        setSpinBox = QSpinBox()
        setSpinBox.setRange(1, 100)
        setSpinBox.setValue(5)
        setSpinBox.setMaximumWidth(80)

        startButton = QPushButton(self.classifyExercises.exercises[index].name)
        startButton.setMaximumWidth(120)

        assignedKey = QPushButton(
            self.classifyExercises.exercises[index].assigned_key[0])
        assignedKey.setStyleSheet('background-color: grey; color: white;')
        assignedKey.setMaximumWidth(50)
        assignedKey.setEnabled(False)

        progress = QProgressBar()
        progress.setMaximumWidth(150)
        progress.setValue(randint(1, 100))
        progress.setAlignment(QtCore.Qt.Alignment.AlignCenter)

        latency = QLabel(str(randint(50, 250)) + 'ms')

        avgLatency = QLabel(str(randint(50, 250)) + 'ms')

        hLayout.addWidget(setSpinBox)
        hLayout.setAlignment(setSpinBox, QtCore.Qt.Alignment.AlignHCenter)
        hLayout.addWidget(startButton)
        hLayout.setAlignment(startButton, QtCore.Qt.Alignment.AlignHCenter)
        hLayout.addWidget(assignedKey)
        hLayout.setAlignment(assignedKey, QtCore.Qt.Alignment.AlignHCenter)
        hLayout.addWidget(progress)
        hLayout.setAlignment(progress, QtCore.Qt.Alignment.AlignHCenter)
        hLayout.addWidget(latency)
        hLayout.setAlignment(latency, QtCore.Qt.Alignment.AlignHCenter)
        hLayout.addWidget(avgLatency)
        hLayout.setAlignment(avgLatency, QtCore.Qt.Alignment.AlignHCenter)

        hLayout.setContentsMargins(0, 10, 0, 10)
        self.exerciseLayouts.append(hLayout)
        return hLayout
Ejemplo n.º 9
0
def makeActions(app):
    actionsLayout = QGridLayout()
    actionsLayout.setVerticalSpacing(5)

    actionsLayout.setRowMinimumHeight(0, 30)
    actionsLayout.setRowMinimumHeight(1, 18)
    actionsLayout.setRowMinimumHeight(2, 50)

    signI = QPushButton("IN")
    signO = QPushButton("OUT")
    signI.setSizePolicy(QSizePolicy.Policy.Expanding,
                        QSizePolicy.Policy.Expanding)
    signI.setStyleSheet(
        'QPushButton {background-color: green; color: white; font-size: 28pt; font-weight: bold}'
    )
    signO.setSizePolicy(QSizePolicy.Policy.Expanding,
                        QSizePolicy.Policy.Expanding)
    signO.setStyleSheet(
        'QPushButton {background-color: red; color: white; font-size: 28pt; font-weight: bold}'
    )

    def doIO(io):
        if currentTable != None and lastSelectedRow != None:
            timeManager.signIO(
                currentTable.item(lastSelectedRow, 0).text(), io)
        else:
            print("No item", currentTable != None, lastSelectedRow != None)
        updateNamesTable()

    signI.clicked.connect(lambda: doIO("i"))
    signO.clicked.connect(lambda: doIO("o"))

    more = QPushButton("More user information")
    newUser = QPushButton("New User")
    graph = QPushButton("Graph")
    update = QPushButton("Update")
    quit = QPushButton("Quit")
    more.setSizePolicy(QSizePolicy.Policy.Minimum,
                       QSizePolicy.Policy.Expanding)
    newUser.setSizePolicy(QSizePolicy.Policy.Minimum,
                          QSizePolicy.Policy.Expanding)
    graph.setSizePolicy(QSizePolicy.Policy.Minimum,
                        QSizePolicy.Policy.Expanding)
    update.setSizePolicy(QSizePolicy.Policy.Minimum,
                         QSizePolicy.Policy.Expanding)
    quit.setSizePolicy(QSizePolicy.Policy.Minimum,
                       QSizePolicy.Policy.Expanding)
    quit.setStyleSheet('QPushButton {color: red}')

    update.clicked.connect(updateNamesTable)
    quit.clicked.connect(lambda: app.closeAllWindows())

    actionsLayout.addWidget(signI, 0, 0, 3, 2)
    actionsLayout.addWidget(signO, 0, 2, 3, 2)
    # actionsLayout.addWidget(more, 0, 4, 2, 1)
    actionsLayout.addWidget(newUser, 2, 4)
    # actionsLayout.addWidget(graph, 0, 5)
    actionsLayout.addWidget(update, 1, 5)
    actionsLayout.addWidget(quit, 2, 5)
    return actionsLayout
Ejemplo n.º 10
0
    def gui_init(self):
        logger.debug('GUI initialization')
        self.setWindowTitle(f'{APP_NAME} {APP_VERSION}')
        self.setWindowIcon(QIcon('media/icon.png'))
        for x in range(SIZE):
            row = []
            for y in range(SIZE):
                btn = QPushButton(text=f'')
                btn.setFixedWidth(BUTTON_WIDTH)
                btn.setFixedHeight(BUTTON_HEIGHT)
                btn.setAccessibleName(f'{x}/{y}')
                btn.setStyleSheet(REGULAR)

                btn.clicked.connect(self.on_click)
                row.append(btn)

                self.layout.addWidget(btn, x, y)

            self.field.append(row)

        self.setLayout(self.layout)
        logger.debug('GUI initialized')
Ejemplo n.º 11
0
 def __init__(self):
     super().__init__()
     self.logger = logging.getLogger(__name__)
     formatter = logging.Formatter(
         fmt="%(asctime)s-%(levelname)s-%(message)s",
         datefmt="%Y-%m-%d %H:%M:%S")
     filehandler = logging.FileHandler(filename="logs.log",
                                       mode="w",
                                       encoding="utf-8")
     handler = QLogger(update_signal=self.update_signal)
     handler.setLevel(logging.INFO)
     filehandler.setLevel(logging.INFO)
     self.logger.setLevel(logging.INFO)
     if os.path.exists("config.json") == False:
         self.gen_conf()
     with open(file="config.json", mode="r",
               encoding="utf-8") as conf_reader:
         conf = json.loads(conf_reader.read())
     debug = bool(conf["debug"])
     if debug == True:
         handler.setLevel(logging.DEBUG)
         filehandler.setLevel(logging.DEBUG)
         self.logger.setLevel(logging.DEBUG)
     handler.setFormatter(formatter)
     filehandler.setFormatter(formatter)
     self.logger.addHandler(handler)
     self.logger.addHandler(filehandler)
     self.logger.debug("当前调试状态:%s" % debug)
     self.resize(1024, 768)
     self.setWindowOpacity(0.9)
     self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
     self.setWindowFlag(Qt.WindowFlags.FramelessWindowHint)
     self.setAutoFillBackground(True)
     self.work = Work(show_qr_signal=self.show_qr_signal,
                      finish_signal=self.finish_signal,
                      close_qr_signal=self.close_qr_signal)
     self.work_thread = QThread()
     self.work.moveToThread(self.work_thread)
     self.main_layout = QGridLayout()
     self.setLayout(self.main_layout)
     self.title = QLabel("ChinaUniOnlineGUI")
     self.title.setStyleSheet(
         "QLabel{border:none;border-radius:5px;background:transparent;color:#9AD3BC;font-size:60px;}"
     )
     self.title.setAlignment(Qt.Alignment.AlignCenter)
     handler.widget.setStyleSheet(
         "QPlainTextEdit{font-family:Microsoft YaHei;background:#F3EAC2;border:none;border-radius:5px;}QScrollBar:vertical,QScrollBar::handle:vertical{background:#F3EAC2;border:none;border-radius:8px;width:16px;}QScrollBar::handle:vertical:hover{background:#F5B461;}QScrollBar::add-page:vertical,QScrollBar::sub-page:vertical{background:#FFFDF9;border:none;border-radius:8px;width:16px;}QScrollBar::down-arrow:vertical,QScrollBar::up-arrow:vertical{background:#F5B461;border:none;border-radius:8px;width:16px;height:16px;}QScrollBar::sub-line:vertical,QScrollBar::add-line:vertical{background:transparent;border:none;}"
     )
     self.control = QVBoxLayout()
     self.control_close = QPushButton()
     self.control_close.setToolTip("关闭")
     self.control_close.setStyleSheet(
         "QPushButton{background:#FFE3ED;border-radius:5px;border:none;}QPushButton:hover{background:#EC524B;}"
     )
     self.contron_max = QPushButton()
     if self.isMaximized() == False:
         self.contron_max.setToolTip("最大化")
     else:
         self.contron_max.setToolTip("还原")
     self.contron_max.setStyleSheet(
         "QPushButton{background:#FFFDF9;border-radius:5px;border:none;}QPushButton:hover{background:#F5B461;}"
     )
     self.control_min = QPushButton()
     self.control_min.setToolTip("最小化")
     self.control_min.setStyleSheet(
         "QPushButton{background:#BEEBE9;border-radius:5px;border:none;}QPushButton:hover{background:#F3EAC2;}"
     )
     self.start_button = QPushButton("开始(&S)")
     self.start_button.setStyleSheet(
         "QPushButton{background:#9BE3DE;border:none;border-radius:5px;font-size:20px;font-family:DengXian;}QPushButton:hover{background:#9AD3BC;}"
     )
     self.start_button.setToolTip("开始")
     self.start_button.setFixedSize(120, 60)
     self.start_button.setDefault(True)
     setting_button = QPushButton("设置")
     setting_button.setToolTip("设置")
     setting_button.setFixedSize(60, 60)
     setting_button.setStyleSheet(
         "QPushButton{background:#9BE3DE;border:none;border-radius:5px;font-size:20px;font-family:DengXian;}QPushButton:hover{background:#9AD3BC;}"
     )
     setting_button.clicked.connect(self.setting_callback)
     start = QHBoxLayout()
     start.addWidget(self.start_button, 2)
     start.addWidget(setting_button, 1)
     self.control_close.clicked.connect(self.close)
     self.control_min.clicked.connect(self.min_callback)
     self.contron_max.clicked.connect(self.max_callback)
     self.start_button.clicked.connect(self.start_callback)
     self.work_thread.started.connect(self.work.start)
     self.finish_signal.connect(self.finish_callback)
     self.close_qr_signal.connect(self.close_qr)
     self.control.addWidget(self.control_min)
     self.control.addWidget(self.contron_max)
     self.control.addWidget(self.control_close)
     self.main_layout.addLayout(self.control, 0, 0)
     self.main_layout.addWidget(self.title, 0, 1)
     self.main_layout.addLayout(start, 0, 2)
     self.main_layout.addWidget(handler.widget, 1, 1)
     self.update_signal.connect(handler.widget.appendPlainText)
     handler.widget.textChanged.connect(handler.scroll_widget_to_bottom)
     self.show_qr_signal.connect(self.show_qr)
     self.logger.debug("已初始化UI")
Ejemplo n.º 12
0
class UI(QWidget):
    update_signal = pyqtSignal(str)
    show_qr_signal = pyqtSignal(bytes)
    finish_signal = pyqtSignal()
    close_qr_signal = pyqtSignal()

    def __init__(self):
        super().__init__()
        self.logger = logging.getLogger(__name__)
        formatter = logging.Formatter(
            fmt="%(asctime)s-%(levelname)s-%(message)s",
            datefmt="%Y-%m-%d %H:%M:%S")
        filehandler = logging.FileHandler(filename="logs.log",
                                          mode="w",
                                          encoding="utf-8")
        handler = QLogger(update_signal=self.update_signal)
        handler.setLevel(logging.INFO)
        filehandler.setLevel(logging.INFO)
        self.logger.setLevel(logging.INFO)
        if os.path.exists("config.json") == False:
            self.gen_conf()
        with open(file="config.json", mode="r",
                  encoding="utf-8") as conf_reader:
            conf = json.loads(conf_reader.read())
        debug = bool(conf["debug"])
        if debug == True:
            handler.setLevel(logging.DEBUG)
            filehandler.setLevel(logging.DEBUG)
            self.logger.setLevel(logging.DEBUG)
        handler.setFormatter(formatter)
        filehandler.setFormatter(formatter)
        self.logger.addHandler(handler)
        self.logger.addHandler(filehandler)
        self.logger.debug("当前调试状态:%s" % debug)
        self.resize(1024, 768)
        self.setWindowOpacity(0.9)
        self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
        self.setWindowFlag(Qt.WindowFlags.FramelessWindowHint)
        self.setAutoFillBackground(True)
        self.work = Work(show_qr_signal=self.show_qr_signal,
                         finish_signal=self.finish_signal,
                         close_qr_signal=self.close_qr_signal)
        self.work_thread = QThread()
        self.work.moveToThread(self.work_thread)
        self.main_layout = QGridLayout()
        self.setLayout(self.main_layout)
        self.title = QLabel("ChinaUniOnlineGUI")
        self.title.setStyleSheet(
            "QLabel{border:none;border-radius:5px;background:transparent;color:#9AD3BC;font-size:60px;}"
        )
        self.title.setAlignment(Qt.Alignment.AlignCenter)
        handler.widget.setStyleSheet(
            "QPlainTextEdit{font-family:Microsoft YaHei;background:#F3EAC2;border:none;border-radius:5px;}QScrollBar:vertical,QScrollBar::handle:vertical{background:#F3EAC2;border:none;border-radius:8px;width:16px;}QScrollBar::handle:vertical:hover{background:#F5B461;}QScrollBar::add-page:vertical,QScrollBar::sub-page:vertical{background:#FFFDF9;border:none;border-radius:8px;width:16px;}QScrollBar::down-arrow:vertical,QScrollBar::up-arrow:vertical{background:#F5B461;border:none;border-radius:8px;width:16px;height:16px;}QScrollBar::sub-line:vertical,QScrollBar::add-line:vertical{background:transparent;border:none;}"
        )
        self.control = QVBoxLayout()
        self.control_close = QPushButton()
        self.control_close.setToolTip("关闭")
        self.control_close.setStyleSheet(
            "QPushButton{background:#FFE3ED;border-radius:5px;border:none;}QPushButton:hover{background:#EC524B;}"
        )
        self.contron_max = QPushButton()
        if self.isMaximized() == False:
            self.contron_max.setToolTip("最大化")
        else:
            self.contron_max.setToolTip("还原")
        self.contron_max.setStyleSheet(
            "QPushButton{background:#FFFDF9;border-radius:5px;border:none;}QPushButton:hover{background:#F5B461;}"
        )
        self.control_min = QPushButton()
        self.control_min.setToolTip("最小化")
        self.control_min.setStyleSheet(
            "QPushButton{background:#BEEBE9;border-radius:5px;border:none;}QPushButton:hover{background:#F3EAC2;}"
        )
        self.start_button = QPushButton("开始(&S)")
        self.start_button.setStyleSheet(
            "QPushButton{background:#9BE3DE;border:none;border-radius:5px;font-size:20px;font-family:DengXian;}QPushButton:hover{background:#9AD3BC;}"
        )
        self.start_button.setToolTip("开始")
        self.start_button.setFixedSize(120, 60)
        self.start_button.setDefault(True)
        setting_button = QPushButton("设置")
        setting_button.setToolTip("设置")
        setting_button.setFixedSize(60, 60)
        setting_button.setStyleSheet(
            "QPushButton{background:#9BE3DE;border:none;border-radius:5px;font-size:20px;font-family:DengXian;}QPushButton:hover{background:#9AD3BC;}"
        )
        setting_button.clicked.connect(self.setting_callback)
        start = QHBoxLayout()
        start.addWidget(self.start_button, 2)
        start.addWidget(setting_button, 1)
        self.control_close.clicked.connect(self.close)
        self.control_min.clicked.connect(self.min_callback)
        self.contron_max.clicked.connect(self.max_callback)
        self.start_button.clicked.connect(self.start_callback)
        self.work_thread.started.connect(self.work.start)
        self.finish_signal.connect(self.finish_callback)
        self.close_qr_signal.connect(self.close_qr)
        self.control.addWidget(self.control_min)
        self.control.addWidget(self.contron_max)
        self.control.addWidget(self.control_close)
        self.main_layout.addLayout(self.control, 0, 0)
        self.main_layout.addWidget(self.title, 0, 1)
        self.main_layout.addLayout(start, 0, 2)
        self.main_layout.addWidget(handler.widget, 1, 1)
        self.update_signal.connect(handler.widget.appendPlainText)
        handler.widget.textChanged.connect(handler.scroll_widget_to_bottom)
        self.show_qr_signal.connect(self.show_qr)
        self.logger.debug("已初始化UI")

    def min_callback(self):
        if self.isMinimized() == False:
            self.showMinimized()

    def max_callback(self):
        if self.isMaximized() == False:
            self.showMaximized()
            self.contron_max.setToolTip("还原")
        else:
            self.showNormal()
            self.contron_max.setToolTip("最大化")

    def start_callback(self):
        self.start_time = time.time()
        self.work_thread.start()
        self.start_button.setEnabled(False)
        self.start_button.setText("执行中...")

    def finish_callback(self):
        self.start_button.setEnabled(True)
        self.start_button.setText("开始")
        passed_time = time.time() - self.start_time
        mins, secs = divmod(passed_time, 60)
        hours, mins = divmod(mins, 60)
        self.logger.info("执行完成,共计用时 {:0>2d}:{:0>2d}:{:0>2d}".format(
            int(hours), int(mins), int(secs)))

    def show_qr(self, qr: bytes):
        title_label = QLabel("请使用微信扫描小程序码完成登陆")
        title_label.setStyleSheet(
            "QLabel{color:#ffe3ed;border:none;background-color:transparent;border-radius:5px;}"
        )
        title_label.setAlignment(Qt.Alignment.AlignCenter)
        title_label.setFixedHeight(20)
        qr_label = QLabel()
        pixmap = QPixmap()
        pixmap.loadFromData(qr)
        qr_label.setPixmap(pixmap)
        qr_label.setStyleSheet(
            "QLabel{color:#ffe3ed;border:none;background-color:transparent;border-radius:5px;}"
        )
        layout_ = QVBoxLayout()
        layout_.addWidget(title_label, 1)
        layout_.addWidget(qr_label, 9)
        self.qr_dialog = QWidget(self)
        self.qr_dialog.setLayout(layout_)
        self.main_layout.addWidget(self.qr_dialog, 1, 1,
                                   Qt.Alignment.AlignCenter)
        self.qr_dialog.show()

    def close_qr(self):
        self.qr_dialog.close()

    def setting_callback(self):
        setting = SettingWindow(parent=self)
        setting.setStyleSheet(
            "QDialog{border:none;border-radius:5px;background:#F3EAC2;}")
        setting.show()

    def gen_conf(self):
        default_conf = {
            "debug": False,
            "hero": {
                "title": "英雄篇",
                "enabled": True,
                "times": 1
            },
            "revival": {
                "title": "复兴篇",
                "enabled": True,
                "times": 1
            },
            "creation": {
                "title": "创新篇",
                "enabled": True,
                "times": 1
            },
            "belief": {
                "title": "信念篇",
                "enabled": True,
                "times": 1
            },
            "limit_time": {
                "title": "限时赛",
                "enabled": True,
                "times": 1
            },
            "rob": {
                "title": "抢十赛",
                "enabled": True,
                "times": 1
            }
        }
        with open(file="config.json", mode="w",
                  encoding="utf-8") as conf_writer:
            conf_writer.write(
                json.dumps(default_conf,
                           indent=4,
                           sort_keys=True,
                           ensure_ascii=False))
        self.logger.info("已生成默认配置文件")

    def mousePressEvent(self, event: QMouseEvent):
        self.logger.debug("触发鼠标按压事件")
        super().mousePressEvent(event)
        self.setFocus()
        self.m_flag = True
        if event.button() == Qt.MouseButtons.LeftButton and self.isMaximized(
        ) == False and self.hasFocus() == True:
            self.old_pos = event.globalPosition()  #获取鼠标相对窗口的位置
            self.logger.debug("已获取鼠标位置")
            self.setCursor(QtGui.QCursor(
                Qt.CursorShape.SizeAllCursor))  #更改鼠标图标

    def mouseMoveEvent(self, event: QMouseEvent):
        self.logger.debug("触发鼠标移动事件")
        super().mouseMoveEvent(event)
        if self.m_flag == True:
            delta_x = int(event.globalPosition().x() - self.old_pos.x())
            delta_y = int(event.globalPosition().y() - self.old_pos.y())
            self.move(self.x() + delta_x, self.y() + delta_y)  #更改窗口位置
            self.logger.debug("已更改窗口位置")
            self.old_pos = event.globalPosition()

    def mouseReleaseEvent(self, event: QMouseEvent):
        self.logger.debug("触发鼠标释放事件")
        super().mouseReleaseEvent(event)
        self.m_flag = False
        self.setCursor(QtGui.QCursor(Qt.CursorShape.ArrowCursor))
Ejemplo n.º 13
0
 def __init__(self, parent: QWidget):
     super().__init__()
     self.logger = logging.getLogger(__name__)
     with open(file="config.json", mode="r",
               encoding="utf-8") as conf_reader:
         self.conf = json.loads(conf_reader.read())
     self.logger.debug("初始化设置界面。设置内容:%s" % self.conf)
     layout = QGridLayout()
     self.setLayout(layout)
     self.setModal(True)
     self.setParent(parent)
     self.resize(400, 300)
     title = QLabel("设置")
     title.setStyleSheet(
         "QLabel{border:none;border-radius:5px;background:transparent;color:#9AD3BC;font-size:20px;}"
     )
     title.setAlignment(Qt.Alignment.AlignCenter)
     layout.addWidget(title, 0, 1, Qt.Alignment.AlignCenter)
     control_close = QPushButton()
     control_close.setStyleSheet(
         "QPushButton{background:#FFE3ED;border-radius:5px;border:none;}QPushButton:hover{background:#EC524B;}"
     )
     control_close.setToolTip("关闭")
     control_close.setFixedHeight(20)
     control_close.clicked.connect(self.close_callback)
     layout.addWidget(control_close, 0, 0)
     debug_check = QCheckBox("调试模式")
     debug_check.setChecked(self.conf["debug"])
     debug_check.setToolTip("单击切换开关状态")
     debug_check.setStyleSheet(
         "QCheckBox::indicator{width:10px;height:10px;border:none;border-radius:5px;background:#9BE3DE;}QCheckBox::indicator:unchecked{background:#BEEBE9;}QCheckBox::indicator:unchecked:hover{background:#9AD3BC;}QCheckBox::indicator:checked{background:#95E1D3;}QCheckBox::indicator:checked:hover{background:#98DED9;}"
     )
     self.content = QGridLayout()
     (x, y) = self.show_setting(conf=self.conf,
                                layout=self.content)  # 返回content的最后一个元素的x,y
     proxy = QGroupBox()
     proxy.setObjectName("proxy")
     proxy_layout = QVBoxLayout()
     proxy_label = QLabel("代理地址:")
     proxy_label.setStyleSheet(
         "QLabel{background:transparent;border:none;}")
     proxy_input = EnhancedEdit()
     proxy_input.setText(self.conf["proxy"])
     proxy_input.setToolTip("格式为协议://IP:端口,留空保持直连")
     proxy_input.setStyleSheet(
         "QLineEdit{border:1px solid #F3EAC2;border-radius:5px;background:transparent;}QLineEdit:hover{border:1px solid #F5B461;}"
     )
     proxy_layout.addWidget(proxy_label)
     proxy_layout.addWidget(proxy_input)
     proxy.setLayout(proxy_layout)
     proxy.setStyleSheet("QGroupBox{border-radius:5px;}")
     proxy.setToolTip("代理设置")
     if y + 1 >= 3:
         y_ = 0
         x_ = x + 1
     else:
         y_ = y + 1
         x_ = x
     self.content.addWidget(proxy, x_, y_)
     self.content.addWidget(debug_check)
     layout.addLayout(self.content, 1, 1)
Ejemplo n.º 14
0
class AboutDialog(QDialog):
    check_update = pyqtSignal(str, bool)

    def __init__(self, parent=None):
        super(AboutDialog, self).__init__(parent)
        self._ver = ''
        self._github = 'https://github.com/rachpt/lanzou-gui'
        self._api_url = 'https://github.com/zaxtyson/LanZouCloud-API'
        self._gitee = 'https://gitee.com/rachpt/lanzou-gui'
        self._home_page = 'https://rachpt.cn/lanzou-gui/'
        self.initUI()
        self.setStyleSheet(others_style)

    def set_values(self, version):
        self._ver = version
        self.lb_name_text.setText(f"v{version}  (点击检查更新)")  # 更新版本

    def show_update(self, ver, msg):
        self.lb_new_ver = QLabel("新版")  # 检测新版
        self.lb_new_ver_msg = QLabel()
        self.lb_new_ver_msg.setOpenExternalLinks(True)
        self.lb_new_ver_msg.setWordWrap(True)
        if ver != '0':
            self.lb_name_text.setText(f"{self._ver}  ➡  {ver}")
        self.lb_new_ver_msg.setText(msg)
        self.lb_new_ver_msg.setMinimumWidth(700)
        if self.form.rowCount() < 5:
            self.form.insertRow(1, self.lb_new_ver, self.lb_new_ver_msg)

    def initUI(self):
        self.setWindowTitle("关于 lanzou-gui")
        about = f'本项目使用PyQt6实现图形界面,可以完成蓝奏云的大部分功能<br/> \
    得益于 <a href="{self._api_url}">API</a> 的功能,可以间接突破单文件最大 100MB 的限制,同时增加了批量上传/下载的功能<br/> \
Python 依赖见<a href="{self._github }/blob/master/requirements.txt">requirements.txt</a>,\
<a href="{self._github}/releases">releases</a> 有打包好了的 Windows 可执行程序,但可能不是最新的'

        project_url = f'<a href="{self._home_page}">主页</a> | <a href="{self._github}">repo</a> | \
                        <a href="{self._gitee}">mirror repo</a>'

        self.logo = QLabel()  # logo
        self.logo.setPixmap(QPixmap(SRC_DIR + "logo2.gif"))
        self.logo.setStyleSheet("background-color:rgb(255,255,255);")
        self.logo.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.lb_qt_ver = QLabel("依赖")  # QT 版本
        self.lb_qt_text = QLabel(
            f"QT: {QT_VERSION_STR}, PyQt: {PYQT_VERSION_STR}")  # QT 版本
        self.lb_name = QLabel("版本")  # 版本
        self.lb_name_text = QPushButton("")  # 版本
        self.lb_name_text.setToolTip("点击检查更新")
        ver_style = "QPushButton {border:none; background:transparent;font-weight:bold;color:blue;}"
        self.lb_name_text.setStyleSheet(ver_style)
        self.lb_name_text.clicked.connect(
            lambda: self.check_update.emit(self._ver, True))
        self.lb_about = QLabel("关于")  # about
        self.lb_about_text = QLabel()
        self.lb_about_text.setText(about)
        self.lb_about_text.setOpenExternalLinks(True)
        self.lb_author = QLabel("作者")  # author
        self.lb_author_mail = QLabel(
            "<a href='mailto:[email protected]'>rachpt</a>")
        self.lb_author_mail.setOpenExternalLinks(True)
        self.lb_update = QLabel("项目")  # 更新
        self.lb_update_url = QLabel(project_url)
        self.lb_update_url.setOpenExternalLinks(True)
        self.buttonBox = QDialogButtonBox()
        self.buttonBox.setOrientation(Qt.Orientation.Horizontal)
        self.buttonBox.setStandardButtons(
            QDialogButtonBox.StandardButton.Close)
        self.buttonBox.button(
            QDialogButtonBox.StandardButton.Close).setText("关闭")
        self.buttonBox.rejected.connect(self.reject)
        self.buttonBox.setStyleSheet(btn_style)

        self.recommend = QLabel(
            "<br />大文件推荐使用 <a href='https://github.com/Aruelius/cloud189'>cloud189-cli</a>"
        )
        self.recommend.setOpenExternalLinks(True)

        self.line = QLine(QPoint(), QPoint(550, 0))
        self.lb_line = QLabel('<html><hr /></html>')

        vbox = QVBoxLayout()
        vbox.addWidget(self.logo)
        vbox.addStretch(1)
        self.form = QFormLayout()
        self.form.setLabelAlignment(Qt.AlignmentFlag.AlignRight)
        self.form.setFormAlignment(Qt.AlignmentFlag.AlignLeft)
        self.form.setHorizontalSpacing(40)
        self.form.setVerticalSpacing(15)
        self.form.addRow(self.lb_qt_ver, self.lb_qt_text)
        self.form.addRow(self.lb_name, self.lb_name_text)
        self.form.addRow(self.lb_update, self.lb_update_url)
        self.form.addRow(self.lb_author, self.lb_author_mail)
        self.form.addRow(self.lb_about, self.lb_about_text)
        self.form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.
                                       AllNonFixedFieldsGrow)  # 覆盖MacOS的默认样式
        vbox.addLayout(self.form)
        vbox.addStretch(1)
        vbox.addWidget(self.recommend)
        vbox.addWidget(self.lb_line)
        donate = QLabel()
        donate.setText("<b>捐助我</b>&nbsp;如果你愿意")
        donate.setAlignment(Qt.AlignmentFlag.AlignCenter)
        hbox = QHBoxLayout()
        hbox.addStretch(2)
        for it in ["wechat", "alipay", "qqpay"]:
            lb = QLabel()
            lb.setPixmap(QPixmap(SRC_DIR + f"{it}.jpg"))
            hbox.addWidget(lb)
        hbox.addStretch(1)
        hbox.addWidget(self.buttonBox)
        vbox.addWidget(donate)
        vbox.addLayout(hbox)
        self.setLayout(vbox)
        self.setMinimumWidth(720)

    def paintEvent(self, event):
        QDialog.paintEvent(self, event)
        if not self.line.isNull():
            painter = QPainter(self)
            pen = QPen(Qt.GlobalColor.red, 3)
            painter.setPen(pen)
            painter.drawLine(self.line)
Ejemplo n.º 15
0
class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('LazyDictionary')
        self.setWindowIcon(QIcon('book.png'))
        self.setFixedHeight(100)
        self.setFixedWidth(300)
        self.label = QLabel('word count: 0', self)
        self.label.setFont(QFont('san serif', 15))
        self.label.move(90, 0)
        self.button()
        self.oneClick = True

    def button(self):
        self.btn0 = QPushButton('Start', self)
        self.btn0.setGeometry(0, 30, 150, 70)
        self.btn0.setStyleSheet('background-color:green')
        self.btn0.setFont(QFont('san serif', 15))
        self.btn1 = QPushButton('Stop', self)
        self.btn1.setGeometry(150, 30, 150, 70)
        self.btn1.setStyleSheet('background-color:grey')
        self.btn1.setFont(QFont('san serif', 15))
        self.btn0.clicked.connect(self.clickButton0)
        self.btn1.clicked.connect(self.clickButton1)

    def clickButton0(self):
        self.btn0.setStyleSheet('background-color:grey')
        self.btn1.setStyleSheet('background-color:red')
        if self.oneClick:
            main.start()
        self.oneClick = False

    def clickButton1(self):
        self.btn1.setStyleSheet('background-color:grey')
        self.btn0.setStyleSheet('background-color:green')
        main.end()
        self.oneClick = True
        
    def checkCount(self):
        text = 'word count: ' + str(htmlparse.wordCount)
        self.label.setText(text)
Ejemplo n.º 16
0
class LoginDialog(QDialog):
    """登录对话框"""

    clicked_ok = pyqtSignal()

    def __init__(self, config):
        super().__init__()
        self._cwd = os.getcwd()
        self._config = config
        self._cookie_assister = 'login_assister.exe'
        self._user = ""
        self._pwd = ""
        self._cookie = {}
        self._del_user = ""
        self.initUI()
        self.setStyleSheet(dialog_qss_style)
        self.setMinimumWidth(560)
        self.name_ed.setFocus()
        # 信号
        self.name_ed.textChanged.connect(self.set_user)
        self.pwd_ed.textChanged.connect(self.set_pwd)
        self.cookie_ed.textChanged.connect(self.set_cookie)

    def update_selection(self, user):
        """显示已经保存的登录用户信息"""
        user_info = self._config.get_user_info(user)
        if user_info:
            self._user = user_info[0]
            self._pwd = user_info[1]
            self._cookie = user_info[2]
        # 更新控件显示内容
        self.name_ed.setText(self._user)
        self.pwd_ed.setText(self._pwd)
        try: text = ";".join([f'{k}={v}' for k, v in self._cookie.items()])
        except: text = ''
        self.cookie_ed.setPlainText(text)

    def initUI(self):
        self.setWindowTitle("登录蓝奏云")
        self.setWindowIcon(QIcon(SRC_DIR + "login.ico"))
        logo = QLabel()
        logo.setPixmap(QPixmap(SRC_DIR + "logo3.gif"))
        logo.setStyleSheet("background-color:rgb(0,153,255);")
        logo.setAlignment(Qt.AlignmentFlag.AlignCenter)

        self.tabs = QTabWidget()
        self.auto_tab = QWidget()
        self.hand_tab = QWidget()

        # Add tabs
        self.tabs.addTab(self.auto_tab,"自动获取Cookie")
        self.tabs.addTab(self.hand_tab,"手动输入Cookie")
        self.auto_get_cookie_ok = AutoResizingTextEdit("🔶点击👇自动获取浏览器登录信息👇")
        self.auto_get_cookie_ok.setReadOnly(True)
        self.auto_get_cookie_btn = QPushButton("自动读取浏览器登录信息")
        auto_cookie_notice = '支持浏览器:Chrome, Chromium, Opera, Edge, Firefox'
        self.auto_get_cookie_btn.setToolTip(auto_cookie_notice)
        self.auto_get_cookie_btn.clicked.connect(self.call_auto_get_cookie)
        self.auto_get_cookie_btn.setStyleSheet("QPushButton {min-width: 210px;max-width: 210px;}")

        self.name_lb = QLabel("&U 用户")
        self.name_lb.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.name_ed = QLineEdit()
        self.name_lb.setBuddy(self.name_ed)

        self.pwd_lb = QLabel("&P 密码")
        self.pwd_lb.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.pwd_ed = QLineEdit()
        self.pwd_ed.setEchoMode(QLineEdit.EchoMode.Password)
        self.pwd_lb.setBuddy(self.pwd_ed)

        self.cookie_lb = QLabel("&Cookie")
        self.cookie_ed = QTextEdit()
        notice = "由于滑动验证的存在,需要输入cookie,cookie请使用浏览器获取\n" + \
            "cookie会保存在本地,下次使用。其格式如下:\n ylogin=value1; phpdisk_info=value2"
        self.cookie_ed.setPlaceholderText(notice)
        self.cookie_lb.setBuddy(self.cookie_ed)

        self.show_input_cookie_btn = QPushButton("显示Cookie输入框")
        self.show_input_cookie_btn.setToolTip(notice)
        self.show_input_cookie_btn.setStyleSheet("QPushButton {min-width: 110px;max-width: 110px;}")
        self.show_input_cookie_btn.clicked.connect(self.change_show_input_cookie)
        self.ok_btn = QPushButton("登录")
        self.ok_btn.clicked.connect(self.change_ok_btn)
        self.cancel_btn = QPushButton("取消")
        self.cancel_btn.clicked.connect(self.change_cancel_btn)
        lb_line_1 = QLabel()
        lb_line_1.setText('<html><hr />切换用户</html>')
        lb_line_2 = QLabel()
        lb_line_2.setText('<html><hr /></html>')

        self.form = QFormLayout()
        self.form.setLabelAlignment(Qt.AlignmentFlag.AlignRight)
        self.form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow)  # 覆盖MacOS的默认样式
        self.form.addRow(self.name_lb, self.name_ed)
        self.form.addRow(self.pwd_lb, self.pwd_ed)
        if is_windows:
            def set_assister_path():
                """设置辅助登录程序路径"""
                assister_path = QFileDialog.getOpenFileName(self, "选择辅助登录程序路径",
                                                            self._cwd, "EXE Files (*.exe)")
                if not assister_path[0]:
                    return None
                assister_path = os.path.normpath(assister_path[0])  # windows backslash
                if assister_path == self._cookie_assister:
                    return None
                self.assister_ed.setText(assister_path)
                self._cookie_assister = assister_path

            self.assister_lb = QLabel("登录辅助程序")
            self.assister_lb.setAlignment(Qt.AlignmentFlag.AlignCenter)
            self.assister_ed = MyLineEdit(self)
            self.assister_ed.setText(self._cookie_assister)
            self.assister_ed.clicked.connect(set_assister_path)
            self.assister_lb.setBuddy(self.assister_ed)
            self.form.addRow(self.assister_lb, self.assister_ed)

        hbox = QHBoxLayout()
        hbox.addWidget(self.show_input_cookie_btn)
        hbox.addStretch(1)
        hbox.addWidget(self.ok_btn)
        hbox.addWidget(self.cancel_btn)

        user_box = QHBoxLayout()
        self.user_num = 0
        self.user_btns = {}
        for user in self._config.users_name:
            user = str(user)  # TODO: 可能需要删掉
            self.user_btns[user] = QDoublePushButton(user)
            self.user_btns[user].setStyleSheet("QPushButton {border:none;}")
            if user == self._config.name:
                self.user_btns[user].setStyleSheet("QPushButton {background-color:rgb(0,153,2);}")
                self.tabs.setCurrentIndex(1)
            self.user_btns[user].setToolTip(f"点击选中,双击切换至用户:{user}")
            self.user_btns[user].doubleClicked.connect(self.choose_user)
            self.user_btns[user].clicked.connect(self.delete_chose_user)
            user_box.addWidget(self.user_btns[user])
            self.user_num += 1
            user_box.addStretch(1)

        self.layout = QVBoxLayout(self)
        self.layout.addWidget(logo)
        vbox = QVBoxLayout()
        if self._config.name:
            vbox.addWidget(lb_line_1)
            user_box.setAlignment(Qt.AlignmentFlag.AlignCenter)
            vbox.addLayout(user_box)
            vbox.addWidget(lb_line_2)
            if self.user_num > 1:
                self.del_user_btn = QPushButton("删除账户")
                self.del_user_btn.setIcon(QIcon(SRC_DIR + "delete.ico"))
                self.del_user_btn.setStyleSheet("QPushButton {min-width: 180px;max-width: 180px;}")
                self.del_user_btn.clicked.connect(self.call_del_chose_user)
                vbox.addWidget(self.del_user_btn)
            else:
                self.del_user_btn = None
            vbox.addStretch(1)

        vbox.addLayout(self.form)
        vbox.addStretch(1)
        vbox.addLayout(hbox)
        vbox.setAlignment(Qt.AlignmentFlag.AlignCenter)

        self.hand_tab.setLayout(vbox)
        auto_cookie_vbox = QVBoxLayout()
        auto_cookie_vbox.addWidget(self.auto_get_cookie_ok)
        auto_cookie_vbox.addWidget(self.auto_get_cookie_btn)
        auto_cookie_vbox.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.auto_tab.setLayout(auto_cookie_vbox)
        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)
        self.update_selection(self._config.name)

    def call_del_chose_user(self):
        if self._del_user:
            if self._del_user != self._config.name:
                self.user_num -= 1
                self._config.del_user(self._del_user)
                self.user_btns[self._del_user].close()
                self._del_user = ""
                if self.user_num <= 1:
                    self.del_user_btn.close()
                    self.del_user_btn = None
                return
            else:
                title = '不能删除'
                msg = '不能删除当前登录账户,请先切换用户!'
        else:
            title = '请选择账户'
            msg = '请单击选择需要删除的账户\n\n注意不能删除当前账户(绿色)'
        message_box = QMessageBox(self)
        message_box.setIcon(QMessageBox.Icon.Critical)
        message_box.setStyleSheet(btn_style)
        message_box.setWindowTitle(title)
        message_box.setText(msg)
        message_box.setStandardButtons(QMessageBox.StandardButton.Close)
        buttonC = message_box.button(QMessageBox.StandardButton.Close)
        buttonC.setText('关闭')
        message_box.exec()

    def delete_chose_user(self):
        """更改单击选中需要删除的用户"""
        user = str(self.sender().text())
        self._del_user = user
        if self.del_user_btn:
            self.del_user_btn.setText(f"删除 <{user}>")

    def choose_user(self):
        """切换用户"""
        user = self.sender().text()
        if user != self._config.name:
            self.ok_btn.setText("切换用户")
        else:
            self.ok_btn.setText("登录")
        self.update_selection(user)

    def change_show_input_cookie(self):
        row_c = 4 if is_windows else 3
        if self.form.rowCount() < row_c:
            self.org_height = self.height()
            self.form.addRow(self.cookie_lb, self.cookie_ed)
            self.show_input_cookie_btn.setText("隐藏Cookie输入框")
            self.change_height = None
            self.adjustSize()
        else:
            if not self.change_height:
                self.change_height = self.height()
            if self.cookie_ed.isVisible():
                self.cookie_lb.setVisible(False)
                self.cookie_ed.setVisible(False)
                self.show_input_cookie_btn.setText("显示Cookie输入框")
                start_height, end_height = self.change_height, self.org_height
            else:
                self.cookie_lb.setVisible(True)
                self.cookie_ed.setVisible(True)
                self.show_input_cookie_btn.setText("隐藏Cookie输入框")
                start_height, end_height = self.org_height, self.change_height
            gm = self.geometry()
            x, y = gm.x(), gm.y()
            wd = self.width()
            self.animation = QPropertyAnimation(self, b'geometry')
            self.animation.setDuration(400)
            self.animation.setStartValue(QRect(x, y, wd, start_height))
            self.animation.setEndValue(QRect(x, y, wd, end_height))
            self.animation.start()

    def set_user(self, user):
        self._user = user
        if not user:
            return None
        if user not in self._config.users_name:
            self.ok_btn.setText("添加用户")
            self.cookie_ed.setPlainText("")
        elif user != self._config.name:
            self.update_selection(user)
            self.ok_btn.setText("切换用户")
        else:
            self.update_selection(user)
            self.ok_btn.setText("登录")

    def set_pwd(self, pwd):
        if self._user in self._config.users_name:
            user_info = self._config.get_user_info(self._user)
            if pwd and pwd != user_info[1]:  # 改变密码,cookie作废
                self.cookie_ed.setPlainText("")
                self._cookie = None
            if not pwd:  # 输入空密码,表示删除对pwd的存储,并使用以前的cookie
                self._cookie = user_info[2]
                try: text = ";".join([f'{k}={v}' for k, v in self._cookie.items()])
                except: text = ''
                self.cookie_ed.setPlainText(text)
        self._pwd = pwd

    def set_cookie(self):
        cookies = self.cookie_ed.toPlainText()
        if cookies:
            try:
                self._cookie = {kv.split("=")[0].strip(" "): kv.split("=")[1].strip(" ") for kv in cookies.split(";") if kv.strip(" ") }
            except: self._cookie = None

    def change_cancel_btn(self):
        self.update_selection(self._config.name)
        self.close()

    def change_ok_btn(self):
        if self._user and self._pwd:
            if self._user not in self._config.users_name:
                self._cookie = None
        if self._cookie:
            up_info = {"name": self._user, "pwd": self._pwd, "cookie": self._cookie, "work_id": -1}
            if self.ok_btn.text() == "切换用户":
                self._config.change_user(self._user)
            else:
                self._config.set_infos(up_info)
            self.clicked_ok.emit()
            self.close()
        elif USE_WEB_ENG:
            self.web = LoginWindow(self._user, self._pwd)
            self.web.cookie.connect(self.get_cookie_by_web)
            self.web.setWindowModality(Qt.WindowModality.ApplicationModal)
            self.web.exec()
        elif os.path.isfile(self._cookie_assister):
            try:
                result = os.popen(f'{self._cookie_assister} {self._user} {self._pwd}')
                cookie = result.read()
                try:
                    self._cookie = {kv.split("=")[0].strip(" "): kv.split("=")[1].strip(" ") for kv in cookie.split(";")}
                except: self._cookie = None
                if not self._cookie:
                    return None
                up_info = {"name": self._user, "pwd": self._pwd, "cookie": self._cookie, "work_id": -1}
                self._config.set_infos(up_info)
                self.clicked_ok.emit()
                self.close()
            except: pass
        else:
            title = '请使用 Cookie 登录或是选择 登录辅助程序'
            msg = '没有输入 Cookie,或者没有找到登录辅助程序!\n\n' + \
                  '推荐使用浏览器获取 cookie 填入 cookie 输入框\n\n' + \
                  '如果不嫌文件体积大,请下载登录辅助程序:\n' + \
                  'https://github.com/rachpt/lanzou-gui/releases'
            message_box = QMessageBox(self)
            message_box.setIcon(QMessageBox.Icon.Critical)
            message_box.setStyleSheet(btn_style)
            message_box.setWindowTitle(title)
            message_box.setText(msg)
            message_box.setStandardButtons(QMessageBox.StandardButton.Close)
            buttonC = message_box.button(QMessageBox.StandardButton.Close)
            buttonC.setText('关闭')
            message_box.exec()

    def get_cookie_by_web(self, cookie):
        """使用辅助登录程序槽函数"""
        self._cookie = cookie
        self._close_dialog()

    def call_auto_get_cookie(self):
        """自动读取浏览器cookie槽函数"""
        try:
            self._cookie = get_cookie_from_browser()
        except Exception as e:
            logger.error(f"Browser_cookie3 Error: {e}")
            self.auto_get_cookie_ok.setPlainText(f"❌获取失败,错误信息\n{e}")
        else:
            if self._cookie:
                self._user = self._pwd = ''
                self.auto_get_cookie_ok.setPlainText("✅获取成功即将登录……")
                QTimer.singleShot(2000, self._close_dialog)
            else:
                self.auto_get_cookie_ok.setPlainText("❌获取失败\n请提前使用支持的浏览器登录蓝奏云,读取前完全退出浏览器!\n支持的浏览器与顺序:\nchrome, chromium, opera, edge, firefox")

    def _close_dialog(self):
        """关闭对话框"""
        up_info = {"name": self._user, "pwd": self._pwd, "cookie": self._cookie}
        self._config.set_infos(up_info)
        self.clicked_ok.emit()
        self.close()
Ejemplo n.º 17
0
class Ui_TrainPanel(object):
    def setupUi(self, TrainPanel):
        self.parent = TrainPanel
        self.mainLayout = QHBoxLayout(TrainPanel)

        self.bigFont = QLabel().font()
        self.bigFont.setPointSize(13)

        self.actionsLayout = QHBoxLayout(TrainPanel)
        # self.checkRecording = QCheckBox(TrainPanel)
        self.calibrateButton = QPushButton("Calibrate", parent=TrainPanel)
        self.calibrateButton.setFont(self.bigFont)
        self.calibrateButton.setStyleSheet(CustomQStyles.buttonStyle)
        self.calibrateButton.setMinimumHeight(50)
        self.calibrateButton.setMaximumWidth(170)
        self.calibrateButton.setMinimumWidth(120)

        self.sessionButton = QPushButton("Session", parent=TrainPanel)
        self.sessionButton.setFont(self.bigFont)
        self.sessionButton.setStyleSheet(CustomQStyles.outlineButtonStyle)
        self.sessionButton.setMinimumHeight(50)
        self.sessionButton.setMaximumWidth(170)
        self.sessionButton.setMinimumWidth(120)

        self.listFiles = QListWidget(TrainPanel)
        self.listFiles.setFont(self.bigFont)
        self.label = QLabel('or select', parent=TrainPanel)
        self.subjectLayout = QVBoxLayout(TrainPanel)
        print("init")

        self.box1 = QGroupBox(parent=TrainPanel)
        self.box2 = QGroupBox(parent=TrainPanel)
        self.wizard = CalibrateWizard(parent=TrainPanel)

        self.setPatientsBox(TrainPanel)  # right panel
        self.setActionsBox(TrainPanel)  # left panel

        self.mainLayout.addWidget(self.box1, stretch=2)
        self.mainLayout.addWidget(self.box2, stretch=3)
        # self.mainLayout.setAlignment(self.box2, Qt.Alignment.AlignCenter)

    # Display progress bar, checkbox - to record new gestures or not, start train
    def setActionsBox(self, TrainPanel):
        hLayout = QVBoxLayout()
        hLayout.addWidget(self.calibrateButton)
        hLayout.addWidget(self.sessionButton)
        hLayout.setAlignment(self.calibrateButton, Qt.Alignment.AlignCenter)
        hLayout.setAlignment(self.sessionButton, Qt.Alignment.AlignCenter)
        self.box2.setLayout(hLayout)

    # Display list of subjects, or new subject
    def setPatientsBox(self, TrainPanel):

        # Button to create new patient
        self.addPatient = QPushButton('Create Patient')
        self.addPatient.setFixedSize(120, 35)
        self.addPatient.setStyleSheet(CustomQStyles.outlineButtonStyle)

        self.label.setSizePolicy(QSizePolicy.Policy.Expanding,
                                 QSizePolicy.Policy.Expanding)
        self.label.setAlignment(QtCore.Qt.Alignment.AlignCenter)

        self.loadPatientList()

        self.listFiles.setStyleSheet(CustomQStyles.listStyle)
        self.listFiles.setFocusPolicy(Qt.FocusPolicy.NoFocus)

        self.subjectLayout.addWidget(self.addPatient)
        self.subjectLayout.setAlignment(self.addPatient,
                                        Qt.Alignment.AlignCenter)
        self.subjectLayout.addWidget(self.label)
        self.subjectLayout.addWidget(self.listFiles)

        self.box1.setLayout(self.subjectLayout)

    def loadPatientList(self):
        self.listFiles.clear()
        self.parent.patients.clear()
        files = [
            f for f in listdir(PATIENTS_PATH) if isfile(join(PATIENTS_PATH, f))
        ]
        for x, ind in zip(files, range(0, len(files))):
            item = QListWidgetItem(x.split('.')[0])
            item.setTextAlignment(Qt.Alignment.AlignHCenter)
            self.listFiles.addItem(item)
            with open(PATIENTS_PATH + x, 'r') as f:
                person_dict = json.load(f)
                patient = Patient(person_dict['Name'], person_dict['Age'],
                                  person_dict['Exercises'])
                self.parent.patients.append(patient)

        print(self.parent.patients)

    def deleteItemsOfLayout(self, layout):
        if layout is not None:
            while layout.count():
                item = layout.takeAt(0)
                widget = item.widget()
                if widget is not None:
                    widget.setParent(None)
                else:
                    self.deleteItemsOfLayout(item.layout())
Ejemplo n.º 18
0
class CalibrateWizard(QWizard):
    def __init__(self, parent):
        super().__init__(parent)
        self.parent = parent
        self.setWizardStyle(QWizard.WizardStyle.ModernStyle)

        # CREATE PAGE 1, LINE EDIT, TITLES
        buttons_layout = [QWizard.WizardButton.NextButton]
        self.page1 = QWizardPage()
        self.page1.setTitle('Select the exercises you wish to do later')
        self.page1.setSubTitle(
            'Below are listed all the available and selected exercises by you.'
        )
        self.listSelection = TwoListSelection()
        # listSelection.addAvailableItems(["item-{}".format(i) for i in range(5)])
        hLayout1 = QHBoxLayout(self.page1)
        hLayout1.addWidget(self.listSelection)

        # CREATE PAGE 2, LABEL, TITLES
        self.page2 = QWizardPage()
        self.page2.setFinalPage(True)
        self.setButtonLayout(buttons_layout)
        self.page2.setTitle('Calibrate every exercise')
        self.page2.setSubTitle(
            'Do every exercise once, record after pressing button.')
        self.contentLayout = QVBoxLayout(self.page2)
        self.hLayout2 = QHBoxLayout()

        # Create progress bar, buttons
        self.actionsLayout = QHBoxLayout()
        self.finishButton = QPushButton('Ready')
        self.finishButton.setStyleSheet(CustomQStyles.buttonStyle)
        self.finishButton.setFixedSize(120, 35)

        self.progress = QProgressBar()
        self.progress.setRange(0, 1)
        self.actionsLayout.addWidget(self.progress)
        self.actionsLayout.setAlignment(self.progress,
                                        Qt.Alignment.AlignBottom)
        self.actionsLayout.addWidget(self.finishButton)
        self.actionsLayout.setAlignment(self.finishButton,
                                        Qt.Alignment.AlignBottom)

        self.contentLayout.addLayout(self.hLayout2)
        self.contentLayout.addLayout(self.actionsLayout)
        self.actionsLayout.setContentsMargins(15, 35, 15, 0)
        itemsTextList = [
            str(self.listSelection.mInput.item(i).text())
            for i in range(self.listSelection.mInput.count())
        ]
        print("items:", itemsTextList)

        self.button(QWizard.WizardButton.NextButton).clicked.connect(
            self.onWizardNextButton)
        self.finishButton.clicked.connect(self.onWizardFinishButton)

        self.addPage(self.page1)
        self.addPage(self.page2)

        # Recording data
        self.buttons = []
        self.images = []
        self.labels = []
        self.exerciseLayouts = []
        self.recordReady = []
        self.recordThread = RecordThread(self.parent.classifyExercises)

        # Training recorded data
        self.trained = False
        self.trainThread = TrainThread(self.parent.classifyExercises)
        self.trainThread.taskFinished.connect(self.onTrainFinished)

    # Send list to next page
    def onWizardNextButton(self):
        self.setPage(1, self.page1)
        self.trained = False
        itemsTextList = [
            str(self.listSelection.mInput.item(i).text())
            for i in range(self.listSelection.mInput.count())
        ]
        # Update list
        if self.parent.classifyExercises is not None:
            self.parent.classifyExercises.UpdateExerciseList(itemsTextList)

        # Set elements on UI
        self.setMinimumWidth(len(itemsTextList) * 200)
        self.deleteItemsOfLayout(self.hLayout2)
        self.images.clear()
        self.labels.clear()
        self.buttons.clear()
        self.recordReady.clear()
        for x, i in zip(itemsTextList, range(len(itemsTextList))):
            self.exerciseLayouts.append(QVBoxLayout())
            self.buttons.append(QPushButton('Record'))
            self.recordReady.append(False)
            image = QLabel()
            image.setPixmap(
                QPixmap(os.getcwd() + "/resources/images/" + itemsTextList[i] +
                        ".png"))
            self.labels.append(QLabel(itemsTextList[i]))
            self.images.append(image)
            self.buttons[i].setFixedSize(100, 35)
            self.buttons[i].clicked.connect(
                functools.partial(self.onRecordExerciseButtonClicked, x, i))
            self.buttons[i].setStyleSheet(CustomQStyles.outlineButtonStyle)
            self.exerciseLayouts[i].addWidget(self.labels[i])
            self.exerciseLayouts[i].addWidget(self.images[i])
            self.exerciseLayouts[i].addWidget(self.buttons[i])
            self.exerciseLayouts[i].setAlignment(self.labels[i],
                                                 Qt.Alignment.AlignCenter)
            self.exerciseLayouts[i].setAlignment(self.images[i],
                                                 Qt.Alignment.AlignCenter)
            self.exerciseLayouts[i].setAlignment(self.buttons[i],
                                                 Qt.Alignment.AlignCenter)
            self.hLayout2.addLayout(self.exerciseLayouts[i])

    def onRecordExerciseButtonClicked(self, exercise, ind):
        print("Recording - ", exercise)
        if self.parent.classifyExercises is not None:
            self.recordThread.exercise = exercise
            self.recordThread.taskFinished.connect(
                functools.partial(self.recordFinished, exercise, ind),
                Qt.ConnectionType.SingleShotConnection)
            self.recordThread.start()
            self.recordReady[ind] = False
            self.buttons[ind].setStyleSheet(CustomQStyles.recordButtonStyle)
            self.images[ind].setPixmap(
                QPixmap(os.getcwd() + "/resources/images/" + exercise +
                        ".png"))

    def recordFinished(self, exercise, index):
        imagePath = os.getcwd() + "/resources/images/" + exercise + ".png"
        if self.recordThread.result == 0:
            imagePath = os.getcwd(
            ) + "/resources/images/" + exercise + "-fail.png"
        elif self.recordThread.result == 1:
            imagePath = os.getcwd(
            ) + "/resources/images/" + exercise + "-success.png"
            self.recordReady[index] = True
        else:
            print("None.")
        self.images[index].setPixmap(QPixmap(imagePath))
        self.buttons[index].setStyleSheet(CustomQStyles.outlineButtonStyle)
        print(self.recordReady)

    def onWizardFinishButton(self):
        if all(x == True for x in self.recordReady):
            print("All recorded!")
            if not self.trained:
                if self.parent.classifyExercises is not None:
                    self.progress.setRange(0, 0)  # indefinite progress bar
                    self.parent.classifyExercises.SaveProcessedData()
                    self.parent.classifyExercises.SavePatientData()
                    self.parent.ui.loadPatientList()
                    self.trainThread.start()

            else:
                self.close()

        else:
            print("Not all recorded!")

    def onTrainFinished(self):
        self.progress.setRange(0, 1)
        self.progress.setValue(1)
        self.trained = True
        CustomMessage.showDialog("Message", "Training model finished!",
                                 QMessageBox.StandardButtons.Ok)
        self.finishButton.setText('Finish')

    def deleteItemsOfLayout(self, layout):
        if layout is not None:
            while layout.count():
                item = layout.takeAt(0)
                widget = item.widget()
                if widget is not None:
                    widget.setParent(None)
                else:
                    self.deleteItemsOfLayout(item.layout())