Example #1
0
class Ui_seal(object):
    """
    印章选择界面
    """
    def __init__(self):
        self.Seal_enum = {"Seal_1": 0, "Seal_2": 1, "Seal_3": 2, "Seal_4": 3}

    def setupUi(self, Form):
        Form.setObjectName("seal")
        Form.resize(314, 188)
        Form.setWindowFlags(Qt.WindowStaysOnTopHint
                            | Qt.FramelessWindowHint)  # 设置无边框、置顶
        Form.setWindowOpacity(0.9)  # 设置透明度
        Form.raise_()
        Form.setStyleSheet("#seal{\
                              background-color: rgba(0, 0, 0, 0);\
                              border-image:url(./Resource/Pic/入纸确认/背景1.png);}")

        self.Seal_type = QComboBox(Form)
        self.Seal_type.setObjectName("seal_type")
        self.Seal_type.setGeometry(QRect(70, 46, 160, 30))
        self.Seal_type.addItem("Seal_1", self.Seal_enum['Seal_1'])
        self.Seal_type.addItem("Seal_2", self.Seal_enum['Seal_2'])
        self.Seal_type.addItem("Seal_3", self.Seal_enum['Seal_3'])
        self.Seal_type.addItem("Seal_4", self.Seal_enum['Seal_4'])
        self.Seal_type.adjustSize()

        self.verify_btn = QPushButton(Form)
        self.verify_btn.setObjectName("verify_btn")
        self.verify_btn.setGeometry(QRect(10, 120, 140, 60))
        self.verify_btn.setStyleSheet("#verify_btn{\
                                          border-image:url(./Resource/Pic/入纸确认/btn_up.png);\
                                          text-align:center;\
                                          font-weight:Regular; \
                                          font-family:SourceHanSansCN-Regular;\
                                          font-size:18px;\
                                          color:#7B7B7B;}")
        self.verify_btn.setText("确认")

        self.cancel_btn = QPushButton(Form)
        self.cancel_btn.setObjectName("cancel_btn")
        self.cancel_btn.setGeometry(QRect(160, 120, 140, 60))
        self.cancel_btn.setStyleSheet("#cancel_btn{\
                                          border-image:url(./Resource/Pic/入纸确认/btn_up.png);\
                                          text-align:center;\
                                          font-weight:Regular; \
                                          font-family:SourceHanSansCN-Regular;\
                                          font-size:18px;\
                                          color:#7B7B7B;}")
        self.cancel_btn.setText("取消")

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

    def retranslateUi(self, Form):
        _translate = QCoreApplication.translate
Example #2
0
class receipt_view(QWidget, person_change_listener):

    __receipt_printouts = None
    __receipt_stack = None
    __person_list = None
    __model = None

    def __init__(self, model):
        super().__init__()
        self.__model = model
        self.__model.add_person_change_listeners(self)
        self.__receipt_printouts = list()
        # self.setWindowTitle("Receipt Tracker")

        self.__person_list = QComboBox()
        self.__person_list.adjustSize()
        self.__person_list.currentIndexChanged.connect(self.display)

        self.__receipt_stack = QStackedWidget()
        # for name in self.__model.get_names():
        #     printout = receipt_printout(name, self.__model)
        #     self.__receipt_printouts.add(printout)
        #     self.__receipt_stack.addWidget(printout)
        #     self.__person_list.addItem(name)

        receipt_layout = QVBoxLayout()
        receipt_layout.addWidget(self.__person_list)
        receipt_layout.addWidget(self.__receipt_stack)

        self.setLayout(receipt_layout)
        self.show()

    def display(self, i):
        self.__receipt_stack.setCurrentIndex(i)

    def person_update(self, model):
        for printout in self.__receipt_printouts:
            self.__receipt_stack.removeWidget(printout)

        for name in model.get_names():
            in_set = False
            for printout in self.__receipt_printouts:
                if name == printout.name:
                    in_set = True
            if not in_set:
                self.__receipt_printouts.append(receipt_printout(name, model))
                self.__person_list.addItem(name)

        for printout in self.__receipt_printouts:
            self.__receipt_stack.addWidget(printout)
Example #3
0
    def tab1_init(self):
        h_layout = QHBoxLayout()
        mac_label = QLabel('MAC:', self.tab1)
        mac_show_lable = QComboBox()
        mac_show_lable.adjustSize()
        h_layout.addWidget(mac_label)
        h_layout.addWidget(mac_show_lable)
        ip_label = QLabel('IP:', self.tab1)
        ip_label.resize(10, 5)
        ip_show = QLabel('', self.tab1)
        h_layout.addWidget(ip_label)
        h_layout.addWidget(ip_show)
        get_infor_tn = QPushButton('获取模块信息', self.tab1)
        con_btn = QPushButton('连接', self.tab1)
        con_result = QLabel(self.tab1)
        con_result.setPixmap(QPixmap('redled.ico'))

        log_record_lable = QLabel('log记录', self.tab1)
        enable_btn = QRadioButton('enable', self.tab1)
        disable_btn = QRadioButton('disable', self.tab1)
        log_browse = QTextBrowser()

        g_layout = QGridLayout()
        g_layout.addLayout(h_layout, 0, 0, 1, 1)
        g_layout.addWidget(mac_show_lable, 0, 1, 1, 1)
        g_layout.addWidget(ip_label, 0, 2, 1, 1)
        g_layout.addWidget(ip_show, 0, 3, 1, 1)
        g_layout.addWidget(get_infor_tn, 0, 4)
        g_layout.addWidget(con_btn, 0, 5, 1, 1)
        g_layout.addWidget(con_result, 0, 6, 1, 1)
        g_layout.addWidget(log_record_lable, 0, 7, 1, 1)
        g_layout.addWidget(enable_btn, 0, 8)
        g_layout.addWidget(enable_btn, 0, 9)
        g_layout.addWidget(disable_btn, 0, 10)
        g_layout.addWidget(log_browse, 1, 0, 1, 10)
        self.tab1.setLayout(g_layout)
Example #4
0
class Window(QWidget, calc_gui.Ui_AppWindow):
    switch_login = pyqtSignal()

    parameters = ['TRL', 'MRL', 'ERL', 'ORL', 'CRL']

    def __init__(self, user):
        QWidget.__init__(self)
        self.setupUi(self)
        self.setStyleSheet(open(style).read())

        self.tabWidget.setTabEnabled(3, False)
        self.tabWidget.setTabEnabled(4, False)
        self.tabWidget.setTabEnabled(5, False)

        self.expert_name = user
        self.params = []
        self.project_num = ''
        self.rad = []
        self.tprl_min = 0
        self.project_state = ''
        self.label_user_name.setText(user)
        self.label_user_name1.setText(user)
        self.label_user_name2.setText(user)
        self.newproject_data = tuple()
        self.saveproject_data = tuple()
        self.risk_flag = True

        self.btn_set_params.clicked.connect(self.set_params)
        self.btn_calculate.clicked.connect(self.calculate)
        self.btn_reset_tasks.clicked.connect(self.reset_tasks)
        self.btn_help.clicked.connect(self.show_help)
        self.btn_save_results.clicked.connect(self.save_results)
        self.btn_change_user.clicked.connect(self.change_user)
        self.btn_change_user1.clicked.connect(self.change_user)
        self.btn_change_user2.clicked.connect(self.change_user)
        self.btn_load_project.clicked.connect(self.load_project_data)
        self.btn_remove_project.clicked.connect(self.remove_project)
        self.btn_load_project2.clicked.connect(self.load_project_data)
        self.btn_new_project.clicked.connect(self.create_dialog)
        self.tabWidget.currentChanged.connect(self.show_user_projects)
        self.btn_report_ugt.clicked.connect(self.report_ugt)
        self.btn_report_risks.clicked.connect(self.report_risks)
        self.save_data = pd.DataFrame(
            columns=['Level', 'Pars_Name', 'Task', 'Task_Comments', 'Original_Task', 'State', 'Parameter'])
        self.normal_risks = {'РТ-нир': 42, 'РТ-окр': 60, 'РТ-произв': 55, 'РТ-инт': 30, 'РТ-эксп': 28, 'РМ-зак': 29,
                             'РМ-треб': 69, 'РМ-цен': 30, 'РМ-конк': 22, 'РМ-прод': 19, 'РО-дог': 29, 'РО-разр': 30,
                             'РО-эксп': 15, 'РЮ-пат': 5, 'РЮ-зак': 9, 'РЭ-экол': 3, 'РП-бюд': 13, 'РП-срок': 14,
                             'РИ-проект': 223}

    @pyqtSlot(int)
    def show_user_projects(self, index):
        if index == 1:
            drafts = check_db.load_project(self.expert_name, 'черновик')
            self.create_table(self.projects_table, drafts)
        elif index == 2:
            complete = check_db.load_project(self.expert_name, 'итог')
            self.create_table(self.projects_table2, complete)
        else:
            pass

    def create_table(self, tab_widget, data):
        tab_widget.setSortingEnabled(False)
        tab_widget.setRowCount(len(data))
        for i in range(len(data)):
            tab_widget.setRowHeight(i, 20)
        for row, form in enumerate(data):
            form = ((str(row + 1)),) + form
            for column, cell in enumerate(form):
                if column == 0:
                    item = QTableWidgetItem(str(row + 1))
                    item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsDragEnabled | Qt.ItemIsEnabled)
                    tab_widget.setColumnWidth(column, 50)
                    item.setTextAlignment(Qt.AlignCenter)
                    tab_widget.setItem(row, column, item)
                else:
                    item = QTableWidgetItem(str(cell))
                    item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsDragEnabled | Qt.ItemIsEnabled)
                    tab_widget.setItem(row, column, item)
        tab_widget.resizeColumnsToContents()
        tab_widget.setColumnWidth(3, 200)
        tab_widget.setSortingEnabled(True)

    def change_user(self):
        self.switch_login.emit()

    def start_project(self, num):
        self.project_num = num
        self.set_param_check(self.parameters, False)
        self.reset_params()
        self.project_state = ''
        temp = []
        for item in self.tab_new_project.children():
            if isinstance(item, QLineEdit):
                temp.append(item.text())
                item.setText("")
        self.newproject_data = tuple(temp)
        self.tabWidget.setTabEnabled(3, True)
        self.tabWidget.setCurrentIndex(3)
        self.num_calcTab.setText(self.project_num)
        self.user_calcTab.setText(self.expert_name)

    def load_project_data(self):
        table = None
        if self.tabWidget.currentIndex() == 1:
            table = self.projects_table
        elif self.tabWidget.currentIndex() == 2:
            table = self.projects_table2
        if len(table.selectedItems()) == 0:
            QMessageBox.about(self, "Внимание!", "Не выбран проект для загрузки!")
        else:
            index = self.tabWidget.currentIndex()
            self.set_param_check(self.parameters, False)
            self.reset_params()
            data = [self.expert_name]
            row = table.currentRow()
            num = table.item(row, 1).text()
            data.append(num)
            date = table.item(row, 6).text()
            data.append(date)
            value = check_db.get_project(data)
            self.newproject_data = (value[3:])
            self.project_state = value[0]
            self.path = value[1]
            self.params = value[2].split(' ')
            self.project_num = num
            self.tabWidget.setTabEnabled(3, True)
            self.tabWidget.setCurrentIndex(3)
            self.btn_calculate.setEnabled(True)
            self.btn_reset_tasks.setEnabled(True)
            self.num_calcTab.setText(self.project_num)
            self.user_calcTab.setText(self.expert_name)
            self.set_param_check(self.params, True)
            try:
                self.create_rows()
            except FileNotFoundError:
                self.tabWidget.setTabEnabled(index, True)
                self.tabWidget.setCurrentIndex(index)
                if self.confirm_msg("Файлы проекта не найдены! Вы хотите удалить выбранный проект из списка?"):
                    self.delete_from_table(table)

    def remove_project(self):
        table = self.projects_table
        if len(self.projects_table.selectedItems()) == 0:
            QMessageBox.about(self, "Внимание!", "Не выбран проект для удаления!")
        else:
            if self.confirm_msg("Вы уверены, что хотите удалить выбранный проект?"):
                self.delete_from_table(table)

    def delete_from_table(self, table):
        data = [self.expert_name]
        row = table.currentRow()
        num = table.item(row, 1).text()
        data.append(num)
        date = table.item(row, 6).text()
        data.append(date)
        file_path = check_db.remove_project(data)
        index = file_path.rfind('/')
        line = file_path.replace('/', '\\')
        dir_path = f'\\{line[:index]}'
        dir = os.getcwd() + dir_path
        try:
            os.remove(file_path)
            os.rmdir(dir)
        except:
            pass
        self.show_user_projects(self.tabWidget.currentIndex())

    def create_dialog(self):
        if self.expert_name == '':
            QMessageBox.about(self, "Внимание!", "Не выбран пользователь!")
            self.switch_login.emit()
        else:
            self.check_enterdata()

    def check_enterdata(self):
        full_info = True
        for item in self.tab_new_project.children():
            if isinstance(item, QLineEdit) and item.text() == '':
                full_info = False
        if not full_info:
            QMessageBox.about(self, "Внимание!", "Не все поля заполнены!")
        else:
            project_num = self.enter_project_num.text()
            self.start_project(project_num)

    def set_param_check(self, params, bool):
        for el in self.group_params.children():
            for param in params:
                if param.lower() in el.objectName().title().lower():
                    el.setChecked(bool)

    def reset_params(self):
        self.path = 'data/Param_Tasks.xlsx'
        self.save_data = pd.DataFrame(
            columns=['Level', 'Pars_Name', 'Task', 'Task_Comments', 'Original_Task', 'State', 'Parameter'])
        self.param_tabs.clear()
        self.params = []
        self.rad = []

    def confirm_msg(self, text):
        messageBox = QMessageBox(self)
        messageBox.setWindowTitle("Подтверждение")
        messageBox.setIcon(QMessageBox.Question)
        messageBox.setText(text)
        buttonYes = messageBox.addButton("Да", QMessageBox.YesRole)
        buttonNo = messageBox.addButton("Нет", QMessageBox.NoRole)
        messageBox.setDefaultButton(buttonYes)
        messageBox.exec_()

        if messageBox.clickedButton() == buttonYes:
            return True
        elif messageBox.clickedButton() == buttonNo:
            return False

    def reset_tasks(self):
        if self.confirm_msg("Вы уверены, что хотите сбросить все отметки?"):
            tab_count = self.param_tabs.count()
            for i in range(tab_count):
                self.param_tabs.setCurrentIndex(i)
                tree = self.param_tabs.currentWidget()
                root = tree.invisibleRootItem()
                for level_num in range(root.childCount()):
                    level = root.child(level_num)
                    for j in range(level.childCount()):
                        child = level.child(j)
                        el = tree.itemWidget(child, 0)
                        if isinstance(el, QComboBox):
                            el.setCurrentText('Нет')
            self.param_tabs.setCurrentIndex(0)

    def set_params(self):
        if self.project_state in ['черновик', 'итог']:
            if self.confirm_msg('Вы уверены, что хотите изменить параметры (текущие отметки будут сброшены)?'):
                self.reset_params()
                self.get_params()
                if len(self.params) == 0:
                    QMessageBox.warning(self, 'Предупреждение', 'Не выбраны параметры оценки!')
                else:
                    self.create_rows()
                    self.btn_calculate.setEnabled(True)
                    self.btn_reset_tasks.setEnabled(True)
        else:
            self.reset_params()
            self.get_params()
            if len(self.params) == 0:
                QMessageBox.warning(self, 'Предупреждение', 'Не выбраны параметры оценки!')
            else:
                self.create_rows()
                self.btn_calculate.setEnabled(True)
                self.btn_reset_tasks.setEnabled(True)

    def get_params(self):
        if self.check_trl.isChecked():
            self.params.append('TRL')
        if self.check_mrl.isChecked():
            self.params.append('MRL')
        if self.check_erl.isChecked():
            self.params.append('ERL')
        if self.check_orl.isChecked():
            self.params.append('ORL')
        if self.check_crl.isChecked():
            self.params.append('CRL')

    def create_rows(self):

        for param in self.params:
            self.data = pd.read_excel(self.path, sheet_name=param)
            self.data['Parameter'] = param
            val = self.make_level_dict(self.data)

            self.tw = TreeWidget()
            self.param_tabs.addTab(self.tw, param)
            self.param_tabs.setCurrentIndex(self.params.index(param))
            self.param_tabs.setTabEnabled(self.params.index(param), True)

            for key, value in val.items():
                self.item_0 = QTreeWidgetItem(self.tw)
                self.item_0.setBackground(0, QColor("#D3D3D3"))
                self.item_0.setText(0, f'Уровень {key}')
                self.item_0.setBackground(1, QColor("#D3D3D3"))
                text = self.word_wrap(value[0], 90)
                self.item_0.setText(1, text)

                for v in value[1:]:
                    self.combo_task = QComboBox()
                    self.combo_task.setObjectName('combo_task')
                    self.combo_task.addItems(['Да', 'Нет', 'Не применимо'])
                    self.combo_task.adjustSize()
                    self.combo_task.setFixedSize(110, 20)
                    self.item_1 = QTreeWidgetItem(self.item_0, ["", ""])
                    if v[2] == 0:
                        self.combo_task.setCurrentText('Нет')
                    elif v[2] == 1:
                        self.combo_task.setCurrentText('Да')
                    else:
                        self.combo_task.setCurrentText('Не применимо')

                    self.tw.setItemWidget(self.item_1, 0, self.combo_task)
                    text = self.word_wrap(v[0], 90)
                    self.item_1.setText(1, text)
                    self.item_1.setBackground(0, QColor('#fcfcfc'))
                    self.item_1.setBackground(1, QColor('#fcfcfc'))
            self.save_data = self.save_data.append(self.data)
        self.param_tabs.setCurrentIndex(0)

    def word_wrap(self, line, x):
        start = 0
        if len(line) > x:
            while len(line) > (start + x):
                index = line.rfind(' ', start, start + x)
                line = (line[:index]).strip() + "\n" + (line[index:]).strip()
                start = index
        return line

    def make_level_dict(self, df):
        dict_levels = {}
        for row in range(df['Level'].shape[0]):
            if df['Level'][row] not in dict_levels:
                dict_levels[df['Level'][row]] = [df['Pars_Name'][row],
                                                 [df['Task'][row],
                                                  df['Task_Comments'][row],
                                                  df['State'][row]]]
            else:
                dict_levels[df['Level'][row]].append([df['Task'][row],
                                                      df['Task_Comments'][row],
                                                      df['State'][row]])
        return dict_levels

    def create_table_rows(self, text_levels):

        self.table_tprl_results.setRowCount(len(text_levels) - 1)
        self.table_tprl_results.setColumnCount(2)
        self.table_tprl_results.setColumnWidth(0, 50)
        self.table_tprl_results.setColumnWidth(1, 700)
        self.table_tprl_results.setStyleSheet('''font-size: 14px;''')

        for key, values in text_levels.items():
            if key == 'TPRL':
                self.label_main_tprl.setText(self.word_wrap(values, 95))

        text_levels.pop('TPRL')
        for i, key in enumerate(text_levels.items()):
            label1 = QLabel(key[0])
            label1.setContentsMargins(5, 5, 5, 5)
            label1.setStyleSheet("border-bottom: 1px solid grey;")
            label_text = self.word_wrap(key[1], 90)
            label2 = QLabel(label_text)
            label2.setContentsMargins(5, 5, 5, 5)
            label2.setStyleSheet("border-bottom: 1px solid grey;")
            self.table_tprl_results.setCellWidget(i, 0, label1)
            self.table_tprl_results.setCellWidget(i, 1, label2)
        self.table_tprl_results.setShowGrid(False)
        self.table_tprl_results.resizeRowsToContents()
        self.table_tprl_results.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.table_tprl_results.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.table_tprl_results.setEnabled(True)
        self.table_tprl_results.setFrameStyle(QFrame.NoFrame)

    def make_text_dict(self, op_data, diction):
        new_text_dict = {}
        for key, value in diction.items():
            for rank in range(op_data['Уровень'].shape[0]):
                if (key == 'TPRL') & (value == '0'):
                    new_text_dict['TPRL'] = 'Уровень зрелости инновационного проекта/технологии  = 0'
                elif (key == 'TPRL') & (value == '--'):
                    new_text_dict['TPRL'] = 'Уровень зрелости инновационного проекта/технологии не рассчитан, т.к. ' \
                                            'не были выбраны все параметры'
                elif op_data['Уровень'][rank] == int(float(value)):
                    new_text_dict[key] = op_data[key][rank]
        return new_text_dict

    def make_text(self):
        op_data = pd.read_excel('data/Levels.xlsx')
        text_dict = {'TPRL': str(self.tprl_min)}
        text_dict.update(self.d3)
        text_levels = self.make_text_dict(op_data, text_dict)
        self.create_table_rows(text_levels)

    def calculate(self):
        self.risk_flag = True
        self.risks_table.setVisible(False)
        self.text_warning = ''
        self.save_data.drop(['State'], axis='columns', inplace=True)
        self.label_project_num.setText(self.project_num)
        self.label_expert_name.setText(self.expert_name)
        self.risks_label_project_num.setText(self.project_num)
        self.risks_label_expert_name.setText(self.expert_name)
        self.tabWidget.setTabEnabled(4, True)
        self.tabWidget.setTabEnabled(5, True)
        self.tabWidget.setCurrentIndex(4)
        self.check_draft.setEnabled(True)
        self.check_draft.setChecked(False)
        self.btn_save_results.setEnabled(True)
        self.d1 = {}
        d2 = {}
        self.d3 = {}
        new_state = []
        l2 = []
        for param in self.params:
            self.param_tabs.setCurrentIndex(self.params.index(param))
            tree = self.param_tabs.currentWidget()
            root = tree.invisibleRootItem()
            levels = root.childCount()
            for level_num in range(levels):
                level = root.child(level_num)
                l1 = []
                for kid in range(level.childCount()):
                    child = level.child(kid)
                    el = tree.itemWidget(child, 0)
                    if isinstance(el, QComboBox):
                        combo_text = el.currentText()
                        if combo_text == 'Да':
                            l1.append(1)
                            new_state.append(1)
                        elif combo_text == 'Нет':
                            l1.append(0)
                            new_state.append(0)
                        else:
                            l1.append(-1)
                            new_state.append(-1)
                if param not in self.d1:
                    l2 = []
                    l2.append(l1)
                    self.d1[param] = l2
                else:
                    self.d1[param].append(l1)

            for key, values in self.d1.items():
                first_list = []
                for value in values:
                    new_list = []
                    for v in range(len(value)):
                        if value[v] == 1:
                            new_list.append(1)
                        if value[v] == 0:
                            new_list.append(0)
                    first_list.append(new_list)
                d2[key] = first_list
        self.save_data['State'] = new_state
        for new_key, new_values in d2.items():
            l_n = []
            for new_value in new_values:
                try:
                    new_value = sum(new_value) / len(new_value)
                    n = Decimal(f'{new_value}')
                    new_value = n.quantize(Decimal('1.0'), rounding='ROUND_HALF_UP')
                except Exception:
                    new_value = 0.0
                l_n.append(new_value)
            d2[new_key] = l_n
        for d2_keys, d2_values in d2.items():
            summary = 0
            for d2_value in range(len(d2_values)):
                if d2_values[d2_value] == 1:
                    if d2_value > 0:
                        if d2_values[d2_value - 1] != 1:
                            self.text_warning = 'Вы не отметили задачи предыдущих уровней.\n' \
                                                'Риски рассчитаны неправильно!!!'
                            self.risk_flag = False
                    summary = d2_value + 1
                elif 0 < d2_values[d2_value] < 1:
                    if summary == d2_value:
                        summary += d2_values[d2_value]
            self.d3[d2_keys] = str(summary)

        if len(self.params) == 5:  # Оценка рисков
            self.risks_table.setVisible(True)
            self.count_risks(self.save_data)
        else:
            self.text_warning = 'Комплексная оценка рисков не проводилась, т.к. не все параметры выбраны!'
            self.risks_table.setVisible(False)
            self.risk_flag = False
        self.risks_warning_label.setText(self.text_warning)
        self.btn_report_risks.setEnabled(self.risk_flag)

        for par in Window.parameters:
            if par not in self.d3.keys():
                self.d3[par] = '0'
        print(self.d3)
        for iter_k, iter_v in self.d3.items():
            # iter_v = round(float(iter_v), 1)

            self.d3[iter_k] = str(iter_v)
        print(self.d3)
        self.param_tabs.setCurrentIndex(0)
        self.frame_results.setEnabled(True)
        self.show_results(self.d3)
        if len(self.params) == 5:
            self.chart = Chart(self.d3, self.lay)
        self.make_text()

    def count_risks(self, frame):
        new_risks = self.normal_risks.copy()
        self.risk_data = pd.DataFrame(
            columns=['Level', 'РТ-нир', 'РТ-окр', 'РТ-произв', 'РТ-инт', 'РТ-эксп', 'РМ-зак', 'РМ-треб',
                     'РМ-цен', 'РМ-конк', 'РМ-прод', 'РО-дог', 'РО-разр', 'РО-эксп', 'РЮ-пат', 'РЮ-зак',
                     'РЭ-экол', 'РП-бюд', 'РП-срок', 'РИ-проект'])
        final_risks = {}
        columns = ['РТ-нир', 'РТ-окр', 'РТ-произв', 'РТ-инт', 'РТ-эксп', 'РМ-зак', 'РМ-треб',
                   'РМ-цен', 'РМ-конк', 'РМ-прод', 'РО-дог', 'РО-разр', 'РО-эксп', 'РЮ-пат', 'РЮ-зак',
                   'РЭ-экол', 'РП-бюд', 'РП-срок']
        for param in self.params:
            risk_d = pd.read_excel('data/Risks.xlsx', sheet_name=param)
            self.risk_data = self.risk_data.append(risk_d)
        self.risk_data.drop(['Level'], axis='columns', inplace=True)
        all_risk = pd.concat([frame, self.risk_data], axis=1)
        all_risk.reset_index(inplace=True)
        for row in all_risk.index:
            if all_risk['State'][row] == 0:
                for col in columns:
                    if all_risk[col][row] == 1:
                        all_risk.at[row, col] = 0
            elif all_risk['State'][row] == -1:
                for col in columns:
                    if all_risk[col][row] == 1:
                        all_risk.at[row, col] = 1
                        new_risks[col] -= 1
                all_risk.loc[row, 'РИ-проект'] = 0
                new_risks['РИ-проект'] -= 1
        for key, values in new_risks.items():
            if key not in final_risks:
                if key == 'РИ-проект':
                    value = round((1 / new_risks[key] * all_risk[all_risk['State'] == 0].shape[0]) * 100, 1)
                else:
                    value = round((1 / new_risks[key] * all_risk[all_risk[key] == 0].shape[0]) * 100, 1)
                if value > 100:
                    value = 100.0
                final_risks[key] = value
        # all_risk.to_excel(f'Data_Risk_{self.project_num}.xlsx', index=False)
        self.create_risk_table(final_risks)

    def create_risk_table(self, dict_risks):
        risk_value = []
        risk_group = [
            "Технический риск", "Технический риск", "Технический риск", "Технологический риск", "Технологический риск",
            "Маркетинговый риск", "Маркетинговый риск", "Маркетинговый риск", "Маркетинговый (коньюнктурный) риск",
            "Маркетинговый риск", "Организационный (контрактный) риск", "Организационный риск", "Организационный риск",
            "Юридический (правовой) риск", "Юридический риск (законодательство)", "Экологический риск",
            "Проектный риск",
            "Проектный риск", "Интегральный проектный риск"
        ]
        risk_text = [
            "Получение отрицательных результатов научно - исследовательских работ",
            "Недостижение запланированных технических параметров в ходе конструкторских и технологических разработок",
            "Низкие технологические возможности производства",
            "Недостаточная проработка вопросов интеграции в систему верхнего уровня",
            "Применение неапробированных в промышленных масштабах технологий",
            "Недостаточные (отсутствующие) исследования потенциальных заказчиков продукта, сегментации рынка",
            "Недостаточные (отсутствующие) исследования требований и потребностей конкретных заказчиков из разных "
            "сегментов рынка",
            "Недостаточные (отсутствующие) исследования покупательной способности заказчиков из разных "
            "сегментов рынка, "
            "вопросов себестоимости, ценообразования и объемов продаж для конкретных заказчиков из разных сегментов",
            "Недостаточные (отсутствующие) исследования аналогов и конкурентов, конкурентных преимуществ, разработки "
            "планов по развитию продукта / технологии в конкурентной среде",
            "Недостаточные (отсутствующие) разработки стратегии продаж (каналы продаж, реклама, продвижение, обратная "
            "связь) и постпродажного обслуживания",
            "Несвоевременное заключение договорных отношений с контрагентами и партнерами",
            "Недостаточная компетентность или нехватка ресурсов персонала компании - разработчика",
            "Эксплуатация персоналом незнакомых технических средств (технологий)",
            "Недостаточная (отсутствующая) патентная защита",
            "Неучтенные законодательные ограничения на продукт / технологию или требования нормативно - "
            "правовых документов",
            "Нарушение экологических стандартов",
            "Недостаточно проработанное (отсутствующее) бюджетное планирование проекта",
            "Недостаточно проработанное (отсутствующее) календарное планирование проекта",
            "Недостаточное выполнение задач повышения зрелости продукта / технологии в рамках заданных характеристик"
        ]

        rows = len(risk_group)
        self.risks_table.setRowCount(rows)
        self.risks_table.setHorizontalHeaderLabels(["Группа", "Наименование риска", "Оценка риска"])
        self.risks_table.horizontalHeaderItem(0).setTextAlignment(Qt.AlignCenter)
        self.risks_table.horizontalHeaderItem(1).setTextAlignment(Qt.AlignCenter)
        self.risks_table.horizontalHeaderItem(2).setTextAlignment(Qt.AlignCenter)

        self.risks_table.setColumnWidth(0, 140)
        self.risks_table.setColumnWidth(1, 525)
        self.risks_table.setColumnWidth(2, 120)
        for k, v in dict_risks.items():
            number = Decimal(f'{v}')
            v = number.quantize(Decimal('1'), rounding='ROUND_HALF_UP')
            risk_value.append(v)
        for i in range(rows):
            label_1 = QLabel(self.word_wrap(risk_group[i], 26))
            label_1.setContentsMargins(5, 5, 5, 5)
            label_1.setStyleSheet("font-size: 11px;")
            label_2 = QLabel(self.word_wrap(risk_text[i], 90))
            label_2.setContentsMargins(5, 5, 5, 5)
            label_2.setStyleSheet("font-size: 11px;")
            label_3 = QLabel(f'{risk_value[i]}%')
            label_3.setContentsMargins(55, 5, 5, 5)
            label_3.setStyleSheet("font-size: 11px;")
            self.risks_table.setCellWidget(i, 0, label_1)
            self.risks_table.setCellWidget(i, 1, label_2)
            self.risks_table.setCellWidget(i, 2, label_3)
        self.risks_table.resizeRowsToContents()
        self.risks_table.setEnabled(True)
        self.risks_table.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.risks_table.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

        # all_risk.to_excel(f'Data_Risk_{self.project_num}.xlsx', index=False)

    def save_results(self):
        # ---------------Формируем dataframe с результатами------------------------
        now = datetime.datetime.now()
        date = now.strftime("%d.%m.%Y %H:%M")
        file_date = now.strftime("%d.%m.%Y %H-%M")
        if self.check_draft.isChecked():
            self.project_state = 'черновик'
        else:
            self.project_state = 'итог'
        chars = ':\/*?<>"|'
        saved_file_name = self.project_num
        for ch in chars:
            if ch in saved_file_name:
                saved_file_name = saved_file_name.replace(ch, '_')
        if '\\' in saved_file_name:
            saved_file_name = saved_file_name.replace('\\', '_')
        project_dir = f'{saved_file_name}_{file_date}'
        new_file_name = f'{saved_file_name}_{file_date}.xlsx'
        total = [[self.expert_name, self.project_num, date, self.label_tprl_min_result.text(),
                  self.label_tprl_average_result.text(), self.label_trl_result.text(),
                  self.label_mrl_result.text(), self.label_erl_result.text(),
                  self.label_orl_result.text(), self.label_crl_result.text(), self.project_state]]
        features = np.array(total)
        columns = ['Expert', 'Project Number', 'Date', 'TPRLmin', 'TPRLaverage', 'TRL', 'MRL', 'ERL', 'ORL', 'CRL',
                   'Статус']
        frame = pd.DataFrame(data=features, columns=columns)
        # ---------------Записываем данные в файл----------------------------------
        file_name = 'Results.xlsx'
        if os.path.isfile(file_name):
            old_frame = pd.read_excel('Results.xlsx')
            old_frame = old_frame.append(frame, ignore_index=True)
            old_frame.to_excel('Results.xlsx', index=False)
        else:
            file = open('Results.xlsx', 'w')
            frame.to_excel('Results.xlsx', index=False)
            file.close()
        # ---------------Записываем данные в файл_2--------------------------------------------
        if not os.path.isdir("Projects"):
            os.mkdir("Projects")
        if not os.path.isdir(f"Projects/{self.expert_name}"):
            os.mkdir(f"Projects/{self.expert_name}")
        if self.project_state == 'черновик':
            if not os.path.isdir(f"Projects/{self.expert_name}/Черновики"):
                os.mkdir(f"Projects/{self.expert_name}/Черновики")
            if not os.path.isdir(f"Projects/{self.expert_name}/Черновики/{saved_file_name}"):
                os.mkdir(f"Projects/{self.expert_name}/Черновики/{saved_file_name}")
            self.path = f"Projects/{self.expert_name}/Черновики/{saved_file_name}/{new_file_name}"
            writer = pd.ExcelWriter(self.path)
            for param in self.params:
                new_save_data = self.save_data.loc[self.save_data['Parameter'].isin([param])]
                new_save_data.drop(['Parameter'], axis='columns', inplace=True)
                new_save_data.to_excel(writer, sheet_name=param, index=False)
                writer.save()
            writer.close()
        else:
            if not os.path.isdir(f"Projects/{self.expert_name}/Завершенные"):
                os.mkdir(f"Projects/{self.expert_name}/Завершенные")
            if not os.path.isdir(f"Projects/{self.expert_name}/Завершенные/{saved_file_name}"):
                os.mkdir(f"Projects/{self.expert_name}/Завершенные/{saved_file_name}")
            self.path = f"Projects/{self.expert_name}/Завершенные/{saved_file_name}/{new_file_name}"
            full_dir = f"Projects/{self.expert_name}/Завершенные/{saved_file_name}"
            writer = pd.ExcelWriter(self.path)
            for param in self.params:
                new_save_data = self.save_data.loc[self.save_data['Parameter'].isin([param])]
                new_save_data.drop(['Parameter'], axis='columns', inplace=True)
                new_save_data.to_excel(writer, sheet_name=param, index=False)
                writer.save()
            writer.close()
            self.chart.save_chart(full_dir, project_dir)

        # сохранение проекта в БД
        params = ' '.join(self.params)
        self.saveproject_data = (date, self.project_state, self.path, params)
        data = self.newproject_data + self.saveproject_data
        check_db.save_project(self.expert_name, data)

        QMessageBox.about(self, 'Сохранение результатов', 'Результаты успешно сохранены')
        self.btn_save_results.setEnabled(False)
        self.check_draft.setEnabled(False)

    def report_ugt(self):
        res_list = [float(self.label_trl_result.text()),
                    float(self.label_mrl_result.text()),
                    float(self.label_erl_result.text()),
                    float(self.label_orl_result.text()),
                    float(self.label_crl_result.text())]
        results = []
        for i in range(len(self.parameters)):
            for param in self.params:
                if self.parameters[i] == param:
                    results.append(res_list[i])
        date = datetime.datetime.now().strftime("%d.%m.%Y %H:%M")
        data = {}
        for param in self.params:
            new_save_data = self.save_data.loc[self.save_data['Parameter'].isin([param])]
            new_save_data.drop(['Parameter'], axis='columns', inplace=True)
            data[param] = new_save_data
        self.pdf_data = (
            [date, self.project_num, self.expert_name, self.params, results, [self.tprl_min, self.label_main_tprl.text()]],
            data
        )
        new_report_ugt = ReportUgt(self.pdf_data, self.d1)
        new_report_ugt.set_data()

    def report_risks(self):
        date = datetime.datetime.now().strftime("%d.%m.%Y %H:%M")
        data = [date, self.project_num, self.expert_name]
        new_report_risks = ReportRisks(data, self.risks_table)

    def show_results(self, res):
        res_list = []
        for k_res, v_res in res.items():
            n = Decimal(f'{v_res}')
            v = n.quantize(Decimal('1.0'), rounding='ROUND_HALF_UP')
            if k_res == 'TRL':
                self.label_trl_result.setText(f'{v}')
            elif k_res == 'MRL':
                self.label_mrl_result.setText(f'{v}')
            elif k_res == 'ERL':
                self.label_erl_result.setText(f'{v}')
            elif k_res == 'ORL':
                self.label_orl_result.setText(f'{v}')
            elif k_res == 'CRL':
                self.label_crl_result.setText(f'{v}')
        show_res = res.copy()
        if len(self.params) < 5:
            self.tprl_average = '--'
            self.tprl_min = '--'
            self.label_tprl_average_result.setText(self.tprl_average)
            self.label_tprl_min_result.setText(self.tprl_min)
        else:
            while float(max(show_res.values())) - float(min(show_res.values())) >= 2:
                x = float(max(show_res.values()))
                for d3_k, d3_v in show_res.items():
                    if float(d3_v) == x:
                        d3_v = round(float(d3_v) - 1, 1)
                    show_res[d3_k] = str(d3_v)
            for new_v in show_res.values():
                res_list.append(float(new_v))
            self.tprl_average = float(sum(res_list) / len(res_list))
            number = Decimal(f'{self.tprl_average}')
            self.tprl_average = number.quantize(Decimal("1.0"), rounding='ROUND_HALF_UP')
            self.tprl_min = int(self.tprl_average)
            self.label_tprl_average_result.setText(str(self.tprl_average))
            self.label_tprl_min_result.setText(str(self.tprl_min))

    def show_help(self):
        self.help_dialog = HelpDialog(self)
        self.help_dialog.show()

    def closeEvent(self, event):
        if self.confirm_msg("Вы уверены, что хотите закрыть программу?"):
            event.accept()
        else:
            event.ignore()
Example #5
0
class SettingsDialog(QWidget):
	"A settings dialog"
	scroll_speed_changed = pyqtSignal()
	init_gallery_rebuild = pyqtSignal(bool)
	init_gallery_eximport = pyqtSignal(object)
	def __init__(self, parent=None):
		super().__init__(parent, flags=Qt.Window)

		self.init_gallery_rebuild.connect(self.accept)

		self.parent_widget = parent
		self.setAttribute(Qt.WA_DeleteOnClose)
		self.resize(700, 500)
		self.restore_values()
		self.initUI()
		self.setWindowTitle('Settings')
		self.show()

	def initUI(self):
		main_layout = QVBoxLayout(self)
		sub_layout = QHBoxLayout()
		# Left Panel
		left_panel = QListWidget()
		left_panel.setViewMode(left_panel.ListMode)
		#left_panel.setIconSize(QSize(40,40))
		left_panel.setTextElideMode(Qt.ElideRight)
		left_panel.setMaximumWidth(200)
		left_panel.itemClicked.connect(self.change)
		#web.setText('Web')
		self.application = QListWidgetItem()
		self.application.setText('Application')
		self.web = QListWidgetItem()
		self.web.setText('Web')
		self.visual = QListWidgetItem()
		self.visual.setText('Visual')
		self.advanced = QListWidgetItem()
		self.advanced.setText('Advanced')
		self.about = QListWidgetItem()
		self.about.setText('About')

		#main.setIcon(QIcon(os.path.join(app_constants.static_dir, 'plus2.png')))
		left_panel.addItem(self.application)
		left_panel.addItem(self.web)
		left_panel.addItem(self.visual)
		left_panel.addItem(self.advanced)
		left_panel.addItem(self.about)
		left_panel.setMaximumWidth(100)

		# right panel
		self.right_panel = QStackedLayout()
		self.init_right_panel()

		# bottom
		bottom_layout = QHBoxLayout()
		ok_btn = QPushButton('Ok')
		ok_btn.clicked.connect(self.accept)
		cancel_btn = QPushButton('Cancel')
		cancel_btn.clicked.connect(self.close)
		info_lbl = QLabel()
		info_lbl.setText('<a href="https://github.com/Pewpews/happypanda">'+
				   'Visit GitHub Repo</a> | Options marked with * requires application restart.')
		info_lbl.setTextFormat(Qt.RichText)
		info_lbl.setTextInteractionFlags(Qt.TextBrowserInteraction)
		info_lbl.setOpenExternalLinks(True)
		self.spacer = QWidget()
		self.spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
		bottom_layout.addWidget(info_lbl, 0, Qt.AlignLeft)
		bottom_layout.addWidget(self.spacer)
		bottom_layout.addWidget(ok_btn, 0, Qt.AlignRight)
		bottom_layout.addWidget(cancel_btn, 0, Qt.AlignRight)

		sub_layout.addWidget(left_panel)
		sub_layout.addLayout(self.right_panel)
		main_layout.addLayout(sub_layout)
		main_layout.addLayout(bottom_layout)

		self.restore_options()


	def change(self, item):
		def curr_index(index):
			if index != self.right_panel.currentIndex():
				self.right_panel.setCurrentIndex(index)
		if item == self.application:
			curr_index(self.application_index)
		elif item == self.web:
			curr_index(self.web_index)
		elif item == self.visual:
			curr_index(self.visual_index)
		elif item == self.advanced:
			curr_index(self.advanced_index)
		elif item == self.about:
			curr_index(self.about_index)

	def restore_values(self):
		#Web
		self.exprops = settings.ExProperties()

		# Visual
		self.high_quality_thumbs = app_constants.HIGH_QUALITY_THUMBS
		self.popup_width = app_constants.POPUP_WIDTH
		self.popup_height = app_constants.POPUP_HEIGHT
		self.style_sheet = app_constants.user_stylesheet_path

		# Advanced
		self.scroll_speed = app_constants.SCROLL_SPEED
		self.cache_size = app_constants.THUMBNAIL_CACHE_SIZE
		self.prefetch_item_amnt = app_constants.PREFETCH_ITEM_AMOUNT

	def restore_options(self):

		# App / General
		self.subfolder_as_chapters.setChecked(app_constants.SUBFOLDER_AS_GALLERY)
		self.extract_gallery_before_opening.setChecked(app_constants.EXTRACT_CHAPTER_BEFORE_OPENING)
		self.open_galleries_sequentially.setChecked(app_constants.OPEN_GALLERIES_SEQUENTIALLY)
		self.scroll_to_new_gallery.setChecked(app_constants.SCROLL_TO_NEW_GALLERIES)
		self.move_imported_gs.setChecked(app_constants.MOVE_IMPORTED_GALLERIES)
		self.move_imported_def_path.setText(app_constants.IMPORTED_GALLERY_DEF_PATH)
		self.open_random_g_chapters.setChecked(app_constants.OPEN_RANDOM_GALLERY_CHAPTERS)
		self.rename_g_source_group.setChecked(app_constants.RENAME_GALLERY_SOURCE)
		self.path_to_unrar.setText(app_constants.unrar_tool_path)
		# App / General / External Viewer
		self.external_viewer_path.setText(app_constants.EXTERNAL_VIEWER_PATH)

		# App / Monitor / Misc
		self.enable_monitor.setChecked(app_constants.ENABLE_MONITOR)
		self.look_new_gallery_startup.setChecked(app_constants.LOOK_NEW_GALLERY_STARTUP)
		self.auto_add_new_galleries.setChecked(app_constants.LOOK_NEW_GALLERY_AUTOADD)
		# App / Monitor / Folders
		for path in app_constants.MONITOR_PATHS:
			self.add_folder_monitor(path)

		# App / Monitor / Ignore list
		for path in app_constants.IGNORE_PATHS:
			self.add_ignore_path(path)

		# Web / General
		if 'g.e-hentai' in app_constants.DEFAULT_EHEN_URL:
			self.default_ehen_url.setChecked(True)
		else:
			self.exhentai_ehen_url.setChecked(True)
		
		self.replace_metadata.setChecked(app_constants.REPLACE_METADATA)
		self.always_first_hit.setChecked(app_constants.ALWAYS_CHOOSE_FIRST_HIT)
		self.web_time_offset.setValue(app_constants.GLOBAL_EHEN_TIME)
		self.continue_a_metadata_fetcher.setChecked(app_constants.CONTINUE_AUTO_METADATA_FETCHER)
		self.use_jpn_title.setChecked(app_constants.USE_JPN_TITLE)
		self.use_gallery_link.setChecked(app_constants.USE_GALLERY_LINK)

		# Web / Download
		if app_constants.HEN_DOWNLOAD_TYPE == 0:
			self.archive_download.setChecked(True)
		else:
			self.torrent_download.setChecked(True)

		self.download_directory.setText(app_constants.DOWNLOAD_DIRECTORY)
		self.torrent_client.setText(app_constants.TORRENT_CLIENT)

		# Web / Exhentai
		self.ipbid_edit.setText(self.exprops.ipb_id)
		self.ipbpass_edit.setText(self.exprops.ipb_pass)

		# Visual / Grid View / Tooltip
		self.grid_tooltip_group.setChecked(app_constants.GRID_TOOLTIP)
		self.visual_grid_tooltip_title.setChecked(app_constants.TOOLTIP_TITLE)
		self.visual_grid_tooltip_author.setChecked(app_constants.TOOLTIP_AUTHOR)
		self.visual_grid_tooltip_chapters.setChecked(app_constants.TOOLTIP_CHAPTERS)
		self.visual_grid_tooltip_status.setChecked(app_constants.TOOLTIP_STATUS)
		self.visual_grid_tooltip_type.setChecked(app_constants.TOOLTIP_TYPE)
		self.visual_grid_tooltip_lang.setChecked(app_constants.TOOLTIP_LANG)
		self.visual_grid_tooltip_descr.setChecked(app_constants.TOOLTIP_DESCR)
		self.visual_grid_tooltip_tags.setChecked(app_constants.TOOLTIP_TAGS)
		self.visual_grid_tooltip_last_read.setChecked(app_constants.TOOLTIP_LAST_READ)
		self.visual_grid_tooltip_times_read.setChecked(app_constants.TOOLTIP_TIMES_READ)
		self.visual_grid_tooltip_pub_date.setChecked(app_constants.TOOLTIP_PUB_DATE)
		self.visual_grid_tooltip_date_added.setChecked(app_constants.TOOLTIP_DATE_ADDED)
		# Visual / Grid View / Gallery
		self.external_viewer_ico.setChecked(app_constants.USE_EXTERNAL_PROG_ICO)
		self.gallery_type_ico.setChecked(app_constants.DISPLAY_GALLERY_TYPE)
		if app_constants.GALLERY_FONT_ELIDE:
			self.gallery_text_elide.setChecked(True)
		else:
			self.gallery_text_fit.setChecked(True)
		self.font_lbl.setText(app_constants.GALLERY_FONT[0])
		self.font_size_lbl.setValue(app_constants.GALLERY_FONT[1])

		def re_enforce(s):
			if s:
				self.search_on_enter.setChecked(True)
		self.search_allow_regex.clicked.connect(re_enforce)

		if app_constants.SEARCH_ON_ENTER:
			self.search_on_enter.setChecked(True)
		else:
			self.search_every_keystroke.setChecked(True)
		# Visual / Grid View / Colors
		self.grid_label_color.setText(app_constants.GRID_VIEW_LABEL_COLOR)
		self.grid_title_color.setText(app_constants.GRID_VIEW_TITLE_COLOR)
		self.grid_artist_color.setText(app_constants.GRID_VIEW_ARTIST_COLOR)


		# Advanced / Gallery / Gallery Text Fixer
		self.g_data_regex_fix_edit.setText(app_constants.GALLERY_DATA_FIX_REGEX)
		self.g_data_replace_fix_edit.setText(app_constants.GALLERY_DATA_FIX_REPLACE)
		self.g_data_fixer_title.setChecked(app_constants.GALLERY_DATA_FIX_TITLE)
		self.g_data_fixer_artist.setChecked(app_constants.GALLERY_DATA_FIX_ARTIST)

		# About / DB Overview
		self.tags_treeview_on_start.setChecked(app_constants.TAGS_TREEVIEW_ON_START)

	def accept(self):
		set = settings.set

		# App / General / Gallery
		app_constants.SUBFOLDER_AS_GALLERY = self.subfolder_as_chapters.isChecked()
		set(app_constants.SUBFOLDER_AS_GALLERY, 'Application', 'subfolder as gallery')
		app_constants.EXTRACT_CHAPTER_BEFORE_OPENING = self.extract_gallery_before_opening.isChecked()
		set(app_constants.EXTRACT_CHAPTER_BEFORE_OPENING, 'Application', 'extract chapter before opening')
		app_constants.OPEN_GALLERIES_SEQUENTIALLY = self.open_galleries_sequentially.isChecked()
		set(app_constants.OPEN_GALLERIES_SEQUENTIALLY, 'Application', 'open galleries sequentially')
		app_constants.SCROLL_TO_NEW_GALLERIES = self.scroll_to_new_gallery.isChecked()
		set(app_constants.SCROLL_TO_NEW_GALLERIES, 'Application', 'scroll to new galleries')
		app_constants.MOVE_IMPORTED_GALLERIES = self.move_imported_gs.isChecked()
		set(app_constants.MOVE_IMPORTED_GALLERIES, 'Application', 'move imported galleries')
		if not self.move_imported_def_path.text() or os.path.exists(self.move_imported_def_path.text()):
			app_constants.IMPORTED_GALLERY_DEF_PATH = self.move_imported_def_path.text()
			set(app_constants.IMPORTED_GALLERY_DEF_PATH, 'Application', 'imported gallery def path')
		app_constants.OPEN_RANDOM_GALLERY_CHAPTERS = self.open_random_g_chapters.isChecked()
		set(app_constants.OPEN_RANDOM_GALLERY_CHAPTERS, 'Application', 'open random gallery chapters')
		app_constants.RENAME_GALLERY_SOURCE = self.rename_g_source_group.isChecked()
		set(app_constants.RENAME_GALLERY_SOURCE, 'Application', 'rename gallery source')
		app_constants.unrar_tool_path = self.path_to_unrar.text()
		set(app_constants.unrar_tool_path, 'Application', 'unrar tool path')
		# App / General / Search
		app_constants.ALLOW_SEARCH_REGEX = self.search_allow_regex.isChecked()
		set(app_constants.ALLOW_SEARCH_REGEX, 'Application', 'allow search regex')
		app_constants.SEARCH_AUTOCOMPLETE = self.search_autocomplete.isChecked()
		set(app_constants.SEARCH_AUTOCOMPLETE, 'Application', 'search autocomplete')
		if self.search_on_enter.isChecked():
			app_constants.SEARCH_ON_ENTER = True
		else:
			app_constants.SEARCH_ON_ENTER = False
		set(app_constants.SEARCH_ON_ENTER, 'Application', 'search on enter')
		# App / General / External Viewer
		if not self.external_viewer_path.text():
			app_constants.USE_EXTERNAL_VIEWER = False
			set(False, 'Application', 'use external viewer')
		else:
			app_constants.USE_EXTERNAL_VIEWER = True
			set(True, 'Application', 'use external viewer')
			app_constants._REFRESH_EXTERNAL_VIEWER = True
		app_constants.EXTERNAL_VIEWER_PATH = self.external_viewer_path.text()
		set(app_constants.EXTERNAL_VIEWER_PATH,'Application', 'external viewer path')
		# App / Monitor / misc
		app_constants.ENABLE_MONITOR = self.enable_monitor.isChecked()
		set(app_constants.ENABLE_MONITOR, 'Application', 'enable monitor')
		app_constants.LOOK_NEW_GALLERY_STARTUP = self.look_new_gallery_startup.isChecked()
		set(app_constants.LOOK_NEW_GALLERY_STARTUP, 'Application', 'look new gallery startup')
		app_constants.LOOK_NEW_GALLERY_AUTOADD = self.auto_add_new_galleries.isChecked()
		set(app_constants.LOOK_NEW_GALLERY_AUTOADD, 'Application', 'look new gallery autoadd')
		# App / Monitor / folders
		paths = []
		folder_p_widgets = self.take_all_layout_widgets(self.folders_layout)
		for x, l_edit in enumerate(folder_p_widgets):
			p = l_edit.text()
			if p:
				paths.append(p)

		set(paths, 'Application', 'monitor paths')
		app_constants.MONITOR_PATHS = paths
		# App / Monitor / ignore list
		paths = []
		ignore_p_widgets = self.take_all_layout_widgets(self.ignore_path_l)
		for x, l_edit in enumerate(ignore_p_widgets):
			p = l_edit.text()
			if p:
				paths.append(p)
		set(paths, 'Application', 'ignore paths')
		app_constants.IGNORE_PATHS = paths

		# Web / Downloader

		if self.archive_download.isChecked():
			app_constants.HEN_DOWNLOAD_TYPE = 0
		else:
			app_constants.HEN_DOWNLOAD_TYPE = 1
		set(app_constants.HEN_DOWNLOAD_TYPE, 'Web', 'hen download type')

		app_constants.DOWNLOAD_DIRECTORY = self.download_directory.text()
		set(app_constants.DOWNLOAD_DIRECTORY, 'Web', 'download directory')

		app_constants.TORRENT_CLIENT = self.torrent_client.text()
		set(app_constants.TORRENT_CLIENT, 'Web', 'torrent client')

		# Web / Metdata
		if self.default_ehen_url.isChecked():
			app_constants.DEFAULT_EHEN_URL = 'http://g.e-hentai.org/'
		else:
			app_constants.DEFAULT_EHEN_URL = 'http://exhentai.org/'
		set(app_constants.DEFAULT_EHEN_URL, 'Web', 'default ehen url')

		app_constants.REPLACE_METADATA = self.replace_metadata.isChecked()
		set(app_constants.REPLACE_METADATA, 'Web', 'replace metadata')

		app_constants.ALWAYS_CHOOSE_FIRST_HIT = self.always_first_hit.isChecked()
		set(app_constants.ALWAYS_CHOOSE_FIRST_HIT, 'Web', 'always choose first hit')

		app_constants.GLOBAL_EHEN_TIME = self.web_time_offset.value()
		set(app_constants.GLOBAL_EHEN_TIME, 'Web', 'global ehen time offset')

		app_constants.CONTINUE_AUTO_METADATA_FETCHER = self.continue_a_metadata_fetcher.isChecked()
		set(app_constants.CONTINUE_AUTO_METADATA_FETCHER, 'Web', 'continue auto metadata fetcher')

		app_constants.USE_JPN_TITLE = self.use_jpn_title.isChecked()
		set(app_constants.USE_JPN_TITLE, 'Web', 'use jpn title')

		app_constants.USE_GALLERY_LINK = self.use_gallery_link.isChecked()
		set(app_constants.USE_GALLERY_LINK, 'Web', 'use gallery link')

		# Web / ExHentai
		self.exprops.ipb_id = self.ipbid_edit.text()
		self.exprops.ipb_pass = self.ipbpass_edit.text()

		# Visual / Grid View / Tooltip
		app_constants.GRID_TOOLTIP = self.grid_tooltip_group.isChecked()
		set(app_constants.GRID_TOOLTIP, 'Visual', 'grid tooltip')
		app_constants.TOOLTIP_TITLE = self.visual_grid_tooltip_title.isChecked()
		set(app_constants.TOOLTIP_TITLE, 'Visual', 'tooltip title')
		app_constants.TOOLTIP_AUTHOR = self.visual_grid_tooltip_author.isChecked()
		set(app_constants.TOOLTIP_AUTHOR, 'Visual', 'tooltip author')
		app_constants.TOOLTIP_CHAPTERS = self.visual_grid_tooltip_chapters.isChecked()
		set(app_constants.TOOLTIP_CHAPTERS, 'Visual', 'tooltip chapters')
		app_constants.TOOLTIP_STATUS = self.visual_grid_tooltip_status.isChecked()
		set(app_constants.TOOLTIP_STATUS, 'Visual', 'tooltip status')
		app_constants.TOOLTIP_TYPE = self.visual_grid_tooltip_type.isChecked()
		set(app_constants.TOOLTIP_TYPE, 'Visual', 'tooltip type')
		app_constants.TOOLTIP_LANG = self.visual_grid_tooltip_lang.isChecked()
		set(app_constants.TOOLTIP_LANG, 'Visual', 'tooltip lang')
		app_constants.TOOLTIP_DESCR = self.visual_grid_tooltip_descr.isChecked()
		set(app_constants.TOOLTIP_DESCR, 'Visual', 'tooltip descr')
		app_constants.TOOLTIP_TAGS = self.visual_grid_tooltip_tags.isChecked()
		set(app_constants.TOOLTIP_TAGS, 'Visual', 'tooltip tags')
		app_constants.TOOLTIP_LAST_READ = self.visual_grid_tooltip_last_read.isChecked()
		set(app_constants.TOOLTIP_LAST_READ, 'Visual', 'tooltip last read')
		app_constants.TOOLTIP_TIMES_READ = self.visual_grid_tooltip_times_read.isChecked()
		set(app_constants.TOOLTIP_TIMES_READ, 'Visual', 'tooltip times read')
		app_constants.TOOLTIP_PUB_DATE = self.visual_grid_tooltip_pub_date.isChecked()
		set(app_constants.TOOLTIP_PUB_DATE, 'Visual', 'tooltip pub date')
		app_constants.TOOLTIP_DATE_ADDED = self.visual_grid_tooltip_date_added.isChecked()
		set(app_constants.TOOLTIP_DATE_ADDED, 'Visual', 'tooltip date added')
		# Visual / Grid View / Gallery
		app_constants.USE_EXTERNAL_PROG_ICO = self.external_viewer_ico.isChecked()
		set(app_constants.USE_EXTERNAL_PROG_ICO, 'Visual', 'use external prog ico')
		app_constants.DISPLAY_GALLERY_TYPE = self.gallery_type_ico.isChecked()
		set(app_constants.DISPLAY_GALLERY_TYPE, 'Visual', 'display gallery type')
		if self.gallery_text_elide.isChecked():
			app_constants.GALLERY_FONT_ELIDE = True
		else:
			app_constants.GALLERY_FONT_ELIDE = False
		set(app_constants.GALLERY_FONT_ELIDE, 'Visual', 'gallery font elide')
		app_constants.GALLERY_FONT = (self.font_lbl.text(), self.font_size_lbl.value())
		set(app_constants.GALLERY_FONT[0], 'Visual', 'gallery font family')
		set(app_constants.GALLERY_FONT[1], 'Visual', 'gallery font size')
		# Visual / Grid View / Colors
		if self.color_checker(self.grid_title_color.text()):
			app_constants.GRID_VIEW_TITLE_COLOR = self.grid_title_color.text()
			set(app_constants.GRID_VIEW_TITLE_COLOR, 'Visual', 'grid view title color')
		if self.color_checker(self.grid_artist_color.text()):
			app_constants.GRID_VIEW_ARTIST_COLOR = self.grid_artist_color.text()
			set(app_constants.GRID_VIEW_ARTIST_COLOR, 'Visual', 'grid view artist color')
		if self.color_checker(self.grid_label_color.text()):
			app_constants.GRID_VIEW_LABEL_COLOR = self.grid_label_color.text()
			set(app_constants.GRID_VIEW_LABEL_COLOR, 'Visual', 'grid view label color')

		# Advanced / Misc
		# Advanced / Misc / Grid View
		app_constants.SCROLL_SPEED = self.scroll_speed
		set(self.scroll_speed, 'Advanced', 'scroll speed')
		self.scroll_speed_changed.emit()
		app_constants.THUMBNAIL_CACHE_SIZE = self.cache_size
		set(self.cache_size[1], 'Advanced', 'cache size')
		QPixmapCache.setCacheLimit(self.cache_size[0]*
							 self.cache_size[1])


		# Advanced / General / Gallery Text Fixer
		app_constants.GALLERY_DATA_FIX_REGEX = self.g_data_regex_fix_edit.text()
		set(app_constants.GALLERY_DATA_FIX_REGEX, 'Advanced', 'gallery data fix regex')
		app_constants.GALLERY_DATA_FIX_TITLE = self.g_data_fixer_title.isChecked()
		set(app_constants.GALLERY_DATA_FIX_TITLE, 'Advanced', 'gallery data fix title')
		app_constants.GALLERY_DATA_FIX_ARTIST = self.g_data_fixer_artist.isChecked()
		set(app_constants.GALLERY_DATA_FIX_ARTIST, 'Advanced', 'gallery data fix artist')
		app_constants.GALLERY_DATA_FIX_REPLACE = self.g_data_replace_fix_edit.text()
		set(app_constants.GALLERY_DATA_FIX_REPLACE, 'Advanced', 'gallery data fix replace')

		# About / DB Overview
		app_constants.TAGS_TREEVIEW_ON_START = self.tags_treeview_on_start.isChecked()
		set(app_constants.TAGS_TREEVIEW_ON_START, 'Application', 'tags treeview on start')

		settings.save()
		self.close()

	def init_right_panel(self):

		#def title_def(title):
		#	title_lbl = QLabel(title)
		#	f = QFont()
		#	f.setPixelSize(16)
		#	title_lbl.setFont(f)
		#	return title_lbl

		def groupbox(name, layout, parent, add_in_layout=None):
			"""
			Makes a groupbox and a layout for you
			Returns groupbox and layout
			"""
			g = QGroupBox(name, parent)
			l = layout(g)
			if add_in_layout:
				if isinstance(add_in_layout, QFormLayout):
					add_in_layout.addRow(g)
				else:
					add_in_layout.addWidget(g)
			return g, l

		def option_lbl_checkbox(text, optiontext, parent=None):
			l = QLabel(text)
			c = QCheckBox(text, parent)
			return l, c

		def new_tab(name, parent, scroll=False):
			"""
			Creates a new tab.
			Returns new tab page widget and it's layout
			"""
			new_t = QWidget(parent)
			new_l = QFormLayout(new_t)
			if scroll:
				scr = QScrollArea(parent)
				scr.setBackgroundRole(QPalette.Base)
				scr.setWidget(new_t)
				scr.setWidgetResizable(True)
				parent.addTab(scr, name)
				return new_t, new_l
			else:
				parent.addTab(new_t, name)
			return new_t, new_l


		# App
		application = QTabWidget(self)
		self.application_index = self.right_panel.addWidget(application)
		application_general, app_general_m_l = new_tab('General', application, True)

		# App / General / gallery
		app_gallery_page, app_gallery_l = new_tab('Gallery', application, True)
		self.subfolder_as_chapters = QCheckBox("Subdirectiories should be treated as standalone galleries instead of chapters (applies in archives too)")
		self.subfolder_as_chapters.setToolTip("This option will enable creating standalone galleries for each subdirectiories found recursively when importing."+
										"\nDefault action is treating each subfolder found as chapters of a gallery.")
		extract_gallery_info = QLabel("Note: This option has no effect when turned off if path to viewer is not specified.")
		self.extract_gallery_before_opening = QCheckBox("Extract archive before opening (only turn off if your viewer supports it)")
		self.open_galleries_sequentially = QCheckBox("Open chapters sequentially (Note: has no effect if path to viewer is not specified)")
		subf_info = QLabel("Behaviour of 'Scan for new galleries on startup' option will be affected.")
		subf_info.setWordWrap(True)
		app_gallery_l.addRow('Note:', subf_info)
		app_gallery_l.addRow(self.subfolder_as_chapters)
		app_gallery_l.addRow(extract_gallery_info)
		app_gallery_l.addRow(self.extract_gallery_before_opening)
		app_gallery_l.addRow(self.open_galleries_sequentially)
		self.scroll_to_new_gallery = QCheckBox("Scroll to newly added gallery")
		self.scroll_to_new_gallery.setDisabled(True)
		app_gallery_l.addRow(self.scroll_to_new_gallery)
		self.move_imported_gs, move_imported_gs_l = groupbox('Move imported galleries',
													   QFormLayout, app_gallery_page)
		self.move_imported_gs.setCheckable(True)
		self.move_imported_gs.setToolTip("Move imported galleries to specified folder.")
		self.move_imported_def_path = PathLineEdit()
		move_imported_gs_l.addRow('Directory:', self.move_imported_def_path)
		app_gallery_l.addRow(self.move_imported_gs)
		self.rename_g_source_group, rename_g_source_l = groupbox('Rename gallery source',
													  QFormLayout, app_gallery_page)
		self.rename_g_source_group.setCheckable(True)
		self.rename_g_source_group.setDisabled(True)
		app_gallery_l.addRow(self.rename_g_source_group)
		rename_g_source_l.addRow(QLabel("Check what to include when renaming gallery source. (Same order)"))
		rename_g_source_flow_l = FlowLayout()
		rename_g_source_l.addRow(rename_g_source_flow_l)
		self.rename_artist = QCheckBox("Artist")
		self.rename_title = QCheckBox("Title")
		self.rename_lang = QCheckBox("Language")
		self.rename_title.setChecked(True)
		self.rename_title.setDisabled(True)
		rename_g_source_flow_l.addWidget(self.rename_artist)
		rename_g_source_flow_l.addWidget(self.rename_title)
		rename_g_source_flow_l.addWidget(self.rename_lang)
		random_gallery_opener, random_g_opener_l = groupbox('Random Gallery Opener', QFormLayout, app_gallery_page)
		app_gallery_l.addRow(random_gallery_opener)
		self.open_random_g_chapters = QCheckBox("Open random gallery chapters")
		random_g_opener_l.addRow(self.open_random_g_chapters)

		# App / General / Search
		app_search, app_search_layout = groupbox('Search', QFormLayout, application_general)
		app_general_m_l.addRow(app_search)
		search_allow_regex_l = QHBoxLayout()
		self.search_allow_regex = QCheckBox()
		self.search_allow_regex.setChecked(app_constants.ALLOW_SEARCH_REGEX)
		self.search_allow_regex.adjustSize()
		self.search_allow_regex.setToolTip('A regex cheatsheet is located at About->Regex Cheatsheet')
		search_allow_regex_l.addWidget(self.search_allow_regex)
		search_allow_regex_l.addWidget(QLabel('A regex cheatsheet is located at About->Regex Cheatsheet'))
		search_allow_regex_l.addWidget(Spacer('h'))
		app_search_layout.addRow('Regex:', search_allow_regex_l)
		# App / General / Search / autocomplete
		self.search_autocomplete = QCheckBox('*')
		self.search_autocomplete.setChecked(app_constants.SEARCH_AUTOCOMPLETE)
		self.search_autocomplete.setToolTip('Turn autocomplete on/off')
		app_search_layout.addRow('Autocomplete', self.search_autocomplete)
		# App / General / Search / search behaviour
		self.search_every_keystroke = QRadioButton('Search on every keystroke *', app_search)
		app_search_layout.addRow(self.search_every_keystroke)
		self.search_on_enter = QRadioButton('Search on return-key *', app_search)
		app_search_layout.addRow(self.search_on_enter)

		# App / General / External Viewer
		app_external_viewer, app_external_viewer_l = groupbox('External Viewer', QFormLayout, application_general, app_general_m_l)
		app_external_viewer_l.addRow(QLabel("Most image viewers should work. Incase it doesn't," +
									   " hit me up on email/github/gitter-chat to add support."))
		self.external_viewer_path = PathLineEdit(app_external_viewer, False, '')
		self.external_viewer_path.setPlaceholderText('Right/Left-click to open folder explorer.'+
							  ' Leave empty to use default viewer')
		self.external_viewer_path.setToolTip('Right/Left-click to open folder explorer.'+
							  ' Leave empty to use default viewer')
		self.external_viewer_path.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
		app_external_viewer_l.addRow('Path:', self.external_viewer_path)

		# App / General / Rar Support
		app_rar_group, app_rar_layout = groupbox('RAR Support *', QFormLayout, self)
		app_general_m_l.addRow(app_rar_group)
		rar_info = QLabel('Specify the path to the unrar tool to enable rar support.\n'+
					'Windows: "unrar.exe" should be in the "bin" directory if you installed from the'+
					' self-extracting archive provided on github.\nOSX: You can install this via HomeBrew.'+
					' Path should be something like: "/usr/local/bin/unrar".\nLinux: Should already be'+
					' installed. You can just type "unrar". If it\'s not installed, use your package manager: pacman -S unrar')
		rar_info.setWordWrap(True)
		app_rar_layout.addRow(rar_info)
		self.path_to_unrar = PathLineEdit(self, False, filters='')
		app_rar_layout.addRow('UnRAR tool path:', self.path_to_unrar)

		# App / Monitor
		app_monitor_page = QScrollArea()
		app_monitor_page.setBackgroundRole(QPalette.Base)
		app_monitor_dummy = QWidget()
		app_monitor_page.setWidgetResizable(True)
		app_monitor_page.setWidget(app_monitor_dummy)
		application.addTab(app_monitor_page, 'Monitoring')
		app_monitor_m_l = QVBoxLayout(app_monitor_dummy)
		# App / Monitor / misc
		app_monitor_misc_group = QGroupBox('General *', self)
		app_monitor_m_l.addWidget(app_monitor_misc_group)
		app_monitor_misc_m_l = QFormLayout(app_monitor_misc_group)
		monitor_info = QLabel('Directory monitoring will monitor the specified directories for any'+
						' filesystem events. For example if you delete a gallery source in one of your'+
						' monitored directories the application will inform you and ask if'+
						' you want to delete the gallery from the application as well.')
		monitor_info.setWordWrap(True)
		app_monitor_misc_m_l.addRow(monitor_info)
		self.enable_monitor = QCheckBox('Enable directory monitoring')
		app_monitor_misc_m_l.addRow(self.enable_monitor)
		self.look_new_gallery_startup = QGroupBox('Scan for new galleries on startup', self)
		app_monitor_misc_m_l.addRow(self.look_new_gallery_startup)
		self.look_new_gallery_startup.setCheckable(True)
		look_new_gallery_startup_m_l = QVBoxLayout(self.look_new_gallery_startup)
		self.auto_add_new_galleries = QCheckBox('Automatically add found galleries')
		look_new_gallery_startup_m_l.addWidget(self.auto_add_new_galleries)

		# App / Monitor / folders
		app_monitor_group = QGroupBox('Directories *', self)
		app_monitor_m_l.addWidget(app_monitor_group, 1)
		app_monitor_folders_m_l = QVBoxLayout(app_monitor_group)
		app_monitor_folders_add = QPushButton('+')
		app_monitor_folders_add.clicked.connect(self.add_folder_monitor)
		app_monitor_folders_add.setMaximumWidth(20)
		app_monitor_folders_add.setMaximumHeight(20)
		app_monitor_folders_m_l.addWidget(app_monitor_folders_add, 0, Qt.AlignRight)
		self.folders_layout = QFormLayout()
		app_monitor_folders_m_l.addLayout(self.folders_layout)

		# App / Ignore
		app_ignore, app_ignore_m_l = new_tab('Ignore', application, True)
		app_ignore_group, app_ignore_list_l = groupbox('List', QVBoxLayout, app_monitor_dummy)
		app_ignore_m_l.addRow(app_ignore_group)
		add_buttons_l = QHBoxLayout()
		app_ignore_add_a = QPushButton('Add archive')
		app_ignore_add_a.clicked.connect(lambda: self.add_ignore_path(dir=False))
		app_ignore_add_f = QPushButton('Add directory')
		app_ignore_add_f.clicked.connect(self.add_ignore_path)
		add_buttons_l.addWidget(app_ignore_add_a, 0, Qt.AlignRight)
		add_buttons_l.addWidget(app_ignore_add_f, 1, Qt.AlignRight)
		app_ignore_list_l.addLayout(add_buttons_l)
		self.ignore_path_l = QFormLayout()
		app_ignore_list_l.addLayout(self.ignore_path_l)

		# Web
		web = QTabWidget(self)
		self.web_index = self.right_panel.addWidget(web)

		# Web / Downloader
		web_downloader, web_downloader_l = new_tab('Downloader', web)
		hen_download_group, hen_download_group_l = groupbox('g.e-hentai/exhentai',
													  QFormLayout, web_downloader)
		web_downloader_l.addRow(hen_download_group)
		self.archive_download = QRadioButton('Archive', hen_download_group)
		self.torrent_download = QRadioButton('Torrent', hen_download_group)
		download_type_l = QHBoxLayout()
		download_type_l.addWidget(self.archive_download)
		download_type_l.addWidget(self.torrent_download, 1)
		hen_download_group_l.addRow('Download Type:', download_type_l)
		self.download_directory = PathLineEdit(web_downloader)
		web_downloader_l.addRow('Destination:', self.download_directory)
		self.torrent_client = PathLineEdit(web_downloader, False, '')
		web_downloader_l.addRow(QLabel("Leave empty to use default torrent client."+
								 "\nIt is NOT recommended to import a file while it's still downloading."))
		web_downloader_l.addRow('Torrent client:', self.torrent_client)

		# Web / Metadata
		web_metadata_page = QScrollArea()
		web_metadata_page.setBackgroundRole(QPalette.Base)
		web_metadata_page.setWidgetResizable(True)
		web.addTab(web_metadata_page, 'Metadata')
		web_metadata_dummy = QWidget()
		web_metadata_page.setWidget(web_metadata_dummy)
		web_metadata_m_l = QFormLayout(web_metadata_dummy)
		self.default_ehen_url = QRadioButton('g.e-hentai.org', web_metadata_page)
		self.exhentai_ehen_url = QRadioButton('exhentai.org', web_metadata_page)
		ehen_url_l = QHBoxLayout()
		ehen_url_l.addWidget(self.default_ehen_url)
		ehen_url_l.addWidget(self.exhentai_ehen_url, 1)
		web_metadata_m_l.addRow('Default URL:', ehen_url_l)
		self.continue_a_metadata_fetcher = QCheckBox('Continue from where auto metadata fetcher left off')
		web_metadata_m_l.addRow(self.continue_a_metadata_fetcher)
		self.use_jpn_title = QCheckBox('Use japanese title')
		self.use_jpn_title.setToolTip('Choose the japenese title over the english one')
		web_metadata_m_l.addRow(self.use_jpn_title)
		time_offset_info = QLabel('We need to impose a delay between our requests to avoid getting banned.'+
							' I have made it so you cannot set the delay lower than the recommended (I don\'t'+
							' want you to get banned, anon!).\nSpecify the delay between requests in seconds.')
		time_offset_info.setWordWrap(True)
		self.web_time_offset = QSpinBox()
		self.web_time_offset.setMaximumWidth(40)
		self.web_time_offset.setMinimum(4)
		self.web_time_offset.setMaximum(99)
		web_metadata_m_l.addRow(time_offset_info)
		web_metadata_m_l.addRow('Requests delay in seconds', self.web_time_offset)
		replace_metadata_info = QLabel('When fetching for metadata the new metadata will be appended'+
								 ' to the gallery by default. This means that new data will only be added if'+
								 ' the field was empty. There is however a special case for namespace & tags.'+
								 ' We go through all the new namespace & tags to only add those that'+
								 ' do not already exists.\n\nEnabling this option makes it so that a gallery\'s old data'+
								 ' are deleted and replaced with the new data.')
		replace_metadata_info.setWordWrap(True)
		self.replace_metadata = QCheckBox('Replace old metadata with new metadata')
		web_metadata_m_l.addRow(replace_metadata_info)
		web_metadata_m_l.addRow(self.replace_metadata)
		first_hit_info = QLabel('By default, you get to choose which gallery to extract metadata from when'+
						  ' there is more than one gallery found when searching.\n'+
						  'Enabling this option makes it choose the first hit, saving you from moving your mouse.')
		first_hit_info.setWordWrap(True)
		self.always_first_hit = QCheckBox('Always choose first hit')
		web_metadata_m_l.addRow(first_hit_info)
		web_metadata_m_l.addRow(self.always_first_hit)
		self.use_gallery_link = QCheckBox('Use current gallery link')
		self.use_gallery_link.setToolTip("Metadata will be fetched from the current gallery link"+
								   " if it's a valid ex/g.e gallery url")
		web_metadata_m_l.addRow(self.use_gallery_link)

		# Web / Exhentai
		exhentai_page = QWidget(self)
		web.addTab(exhentai_page, 'ExHentai')
		ipb_layout = QFormLayout()
		exhentai_page.setLayout(ipb_layout)
		self.ipbid_edit = QLineEdit()
		self.ipbpass_edit = QLineEdit()
		exh_tutorial = QLabel(app_constants.EXHEN_COOKIE_TUTORIAL)
		exh_tutorial.setTextFormat(Qt.RichText)
		ipb_layout.addRow('IPB Member ID:', self.ipbid_edit)
		ipb_layout.addRow('IPB Pass Hash:', self.ipbpass_edit)
		ipb_layout.addRow(exh_tutorial)

		# Visual
		visual = QTabWidget(self)
		self.visual_index = self.right_panel.addWidget(visual)
		visual_general_page = QWidget()
		visual.addTab(visual_general_page, 'General')

		grid_view_general_page = QWidget()
		visual.addTab(grid_view_general_page, 'Grid View')
		grid_view_layout = QVBoxLayout()
		grid_view_layout.addWidget(QLabel('Options marked with * requires application restart'),
						   0, Qt.AlignTop)
		grid_view_general_page.setLayout(grid_view_layout)
		# grid view
		# grid view / tooltip
		self.grid_tooltip_group = QGroupBox('Tooltip', grid_view_general_page)
		self.grid_tooltip_group.setCheckable(True)
		grid_view_layout.addWidget(self.grid_tooltip_group, 0, Qt.AlignTop)
		grid_tooltip_layout = QFormLayout()
		self.grid_tooltip_group.setLayout(grid_tooltip_layout)
		grid_tooltip_layout.addRow(QLabel('Control what is'+
									' displayed in the tooltip when hovering a gallery'))
		grid_tooltips_hlayout = FlowLayout()
		grid_tooltip_layout.addRow(grid_tooltips_hlayout)
		self.visual_grid_tooltip_title = QCheckBox('Title')
		grid_tooltips_hlayout.addWidget(self.visual_grid_tooltip_title)
		self.visual_grid_tooltip_author = QCheckBox('Author')
		grid_tooltips_hlayout.addWidget(self.visual_grid_tooltip_author)
		self.visual_grid_tooltip_chapters = QCheckBox('Chapters')
		grid_tooltips_hlayout.addWidget(self.visual_grid_tooltip_chapters)
		self.visual_grid_tooltip_status = QCheckBox('Status')
		grid_tooltips_hlayout.addWidget(self.visual_grid_tooltip_status)
		self.visual_grid_tooltip_type = QCheckBox('Type')
		grid_tooltips_hlayout.addWidget(self.visual_grid_tooltip_type)
		self.visual_grid_tooltip_lang = QCheckBox('Language')
		grid_tooltips_hlayout.addWidget(self.visual_grid_tooltip_lang)
		self.visual_grid_tooltip_descr = QCheckBox('Description')
		grid_tooltips_hlayout.addWidget(self.visual_grid_tooltip_descr)
		self.visual_grid_tooltip_tags = QCheckBox('Tags')
		grid_tooltips_hlayout.addWidget(self.visual_grid_tooltip_tags)
		self.visual_grid_tooltip_last_read = QCheckBox('Last read')
		grid_tooltips_hlayout.addWidget(self.visual_grid_tooltip_last_read)
		self.visual_grid_tooltip_times_read = QCheckBox('Times read')
		grid_tooltips_hlayout.addWidget(self.visual_grid_tooltip_times_read)
		self.visual_grid_tooltip_pub_date = QCheckBox('Publication Date')
		grid_tooltips_hlayout.addWidget(self.visual_grid_tooltip_pub_date)
		self.visual_grid_tooltip_date_added = QCheckBox('Date added')
		grid_tooltips_hlayout.addWidget(self.visual_grid_tooltip_date_added)
		# grid view / gallery
		grid_gallery_group = QGroupBox('Gallery', grid_view_general_page)
		grid_view_layout.addWidget(grid_gallery_group, 0, Qt.AlignTop)
		grid_gallery_main_l = QFormLayout()
		grid_gallery_main_l.setFormAlignment(Qt.AlignLeft)
		grid_gallery_group.setLayout(grid_gallery_main_l)
		grid_gallery_display = FlowLayout()
		grid_gallery_main_l.addRow('Display icon on gallery:', grid_gallery_display)
		self.external_viewer_ico = QCheckBox('External Viewer')
		grid_gallery_display.addWidget(self.external_viewer_ico)
		self.gallery_type_ico = QCheckBox('File Type')
		grid_gallery_display.addWidget(self.gallery_type_ico)
		if sys.platform.startswith('darwin'):
			grid_gallery_group.setEnabled(False)
		gallery_text_mode = QWidget()
		grid_gallery_main_l.addRow('Text Mode:', gallery_text_mode)
		gallery_text_mode_l = QHBoxLayout()
		gallery_text_mode.setLayout(gallery_text_mode_l)
		self.gallery_text_elide = QRadioButton('Elide text', gallery_text_mode)
		self.gallery_text_fit = QRadioButton('Fit text', gallery_text_mode)
		gallery_text_mode_l.addWidget(self.gallery_text_elide, 0, Qt.AlignLeft)
		gallery_text_mode_l.addWidget(self.gallery_text_fit, 0, Qt.AlignLeft)
		gallery_text_mode_l.addWidget(Spacer('h'), 1, Qt.AlignLeft)
		gallery_font = QHBoxLayout()
		grid_gallery_main_l.addRow('Font:*', gallery_font)
		self.font_lbl = QLabel()
		self.font_size_lbl = QSpinBox()
		self.font_size_lbl.setMaximum(100)
		self.font_size_lbl.setMinimum(1)
		self.font_size_lbl.setToolTip('Font size in pixels')
		choose_font = QPushButton('Choose font')
		choose_font.clicked.connect(self.choose_font)
		gallery_font.addWidget(self.font_lbl, 0, Qt.AlignLeft)
		gallery_font.addWidget(self.font_size_lbl, 0, Qt.AlignLeft)
		gallery_font.addWidget(choose_font, 0, Qt.AlignLeft)
		gallery_font.addWidget(Spacer('h'), 1, Qt.AlignLeft)
		# grid view / colors
		grid_colors_group = QGroupBox('Colors', grid_view_general_page)
		grid_view_layout.addWidget(grid_colors_group, 1, Qt.AlignTop)
		grid_colors_l = QFormLayout()
		grid_colors_group.setLayout(grid_colors_l)
		def color_lineedit():
			l = QLineEdit()
			l.setPlaceholderText('Hex colors. Eg.: #323232')
			l.setMaximumWidth(200)
			return l
		self.grid_label_color = color_lineedit()
		self.grid_title_color = color_lineedit()
		self.grid_artist_color = color_lineedit()
		grid_colors_l.addRow('Label color:', self.grid_label_color)
		grid_colors_l.addRow('Title color:', self.grid_title_color)
		grid_colors_l.addRow('Artist color:', self.grid_artist_color)

		style_page = QWidget(self)
		visual.addTab(style_page, 'Style')
		visual.setTabEnabled(0, False)
		visual.setTabEnabled(2, False)
		visual.setCurrentIndex(1)

		# Advanced
		advanced = QTabWidget(self)
		self.advanced_index = self.right_panel.addWidget(advanced)
		advanced_misc_scroll = QScrollArea(self)
		advanced_misc_scroll.setBackgroundRole(QPalette.Base)
		advanced_misc_scroll.setWidgetResizable(True)
		advanced_misc = QWidget()
		advanced_misc_scroll.setWidget(advanced_misc)
		advanced.addTab(advanced_misc_scroll, 'Misc')
		advanced_misc_main_layout = QVBoxLayout()
		advanced_misc.setLayout(advanced_misc_main_layout)
		misc_controls_layout = QFormLayout()
		advanced_misc_main_layout.addLayout(misc_controls_layout)
		# Advanced / Misc / Grid View
		misc_gridview = QGroupBox('Grid View')
		misc_controls_layout.addWidget(misc_gridview)
		misc_gridview_layout = QFormLayout()
		misc_gridview.setLayout(misc_gridview_layout)
		# Advanced / Misc / Grid View / scroll speed
		scroll_speed_spin_box = QSpinBox()
		scroll_speed_spin_box.setFixedWidth(60)
		scroll_speed_spin_box.setToolTip('Control the speed when scrolling in'+
								   ' grid view. DEFAULT: 7')
		scroll_speed_spin_box.setValue(self.scroll_speed)
		def scroll_speed(v): self.scroll_speed = v
		scroll_speed_spin_box.valueChanged[int].connect(scroll_speed)
		misc_gridview_layout.addRow('Scroll speed:', scroll_speed_spin_box)
		# Advanced / Misc / Grid View / cache size
		cache_size_spin_box = QSpinBox()
		cache_size_spin_box.setFixedWidth(120)
		cache_size_spin_box.setMaximum(999999999)
		cache_size_spin_box.setToolTip('This can greatly reduce lags/freezes in the grid view.' +
								 ' Increase the value if you experience lag when scrolling'+
								 ' through galleries. DEFAULT: 200 MiB')
		def cache_size(c): self.cache_size = (self.cache_size[0], c)
		cache_size_spin_box.setValue(self.cache_size[1])
		cache_size_spin_box.valueChanged[int].connect(cache_size)
		misc_gridview_layout.addRow('Cache Size (MiB):', cache_size_spin_box)

		# Advanced / Gallery
		advanced_gallery, advanced_gallery_m_l = new_tab('Gallery', advanced)
		def rebuild_thumbs():
			confirm_msg = QMessageBox(QMessageBox.Question, '', 'Are you sure you want to regenerate your thumbnails.',
							 QMessageBox.Yes | QMessageBox.No, self)
			if confirm_msg.exec() == QMessageBox.Yes:
				clear_cache_confirm = QMessageBox(QMessageBox.Question, '',
									  'Do you want to delete all old thumbnails before regenerating?', QMessageBox.Yes | QMessageBox.No,
									  self)
				clear_cache = False
				if clear_cache_confirm.exec() == QMessageBox.Yes:
					clear_cache = True
				gallerydb.DatabaseEmitter.RUN = False
				def start_db_activity(): gallerydb.DatabaseEmitter.RUN = True
				app_popup = ApplicationPopup(self.parent_widget)
				app_popup.info_lbl.setText("Regenerating thumbnails...")
				app_popup.admin_db = gallerydb.AdminDB()
				app_popup.admin_db.moveToThread(app_constants.GENERAL_THREAD)
				app_popup.admin_db.DONE.connect(app_popup.admin_db.deleteLater)
				app_popup.admin_db.DONE.connect(start_db_activity)
				app_popup.admin_db.DATA_COUNT.connect(app_popup.prog.setMaximum)
				app_popup.admin_db.PROGRESS.connect(app_popup.prog.setValue)
				self.init_gallery_rebuild.connect(app_popup.admin_db.rebuild_thumbs)
				app_popup.adjustSize()
				self.init_gallery_rebuild.emit(clear_cache)
				app_popup.show()

		rebuild_thumbs_info = QLabel("Clears thumbnail cache and rebuilds it, which can take a while. Tip: Useful when changing thumbnail size.")
		rebuild_thumbs_btn = QPushButton('Regenerate Thumbnails')
		rebuild_thumbs_btn.adjustSize()
		rebuild_thumbs_btn.setFixedWidth(rebuild_thumbs_btn.width())
		rebuild_thumbs_btn.clicked.connect(rebuild_thumbs)
		advanced_gallery_m_l.addRow(rebuild_thumbs_info)
		advanced_gallery_m_l.addRow(rebuild_thumbs_btn)
		g_data_fixer_group, g_data_fixer_l =  groupbox('Gallery Renamer', QFormLayout, advanced_gallery)
		g_data_fixer_group.setEnabled(False)
		advanced_gallery_m_l.addRow(g_data_fixer_group)
		g_data_regex_fix_lbl = QLabel("Rename a gallery through regular expression."+
								" A regex cheatsheet is located at About -> Regex Cheatsheet.")
		g_data_regex_fix_lbl.setWordWrap(True)
		g_data_fixer_l.addRow(g_data_regex_fix_lbl)
		self.g_data_regex_fix_edit = QLineEdit()
		self.g_data_regex_fix_edit.setPlaceholderText("Valid regex")
		g_data_fixer_l.addRow('Regex:', self.g_data_regex_fix_edit)
		self.g_data_replace_fix_edit = QLineEdit()
		self.g_data_replace_fix_edit.setPlaceholderText("Leave empty to delete matches")
		g_data_fixer_l.addRow('Replace with:', self.g_data_replace_fix_edit)
		g_data_fixer_options = FlowLayout()
		g_data_fixer_l.addRow(g_data_fixer_options)
		self.g_data_fixer_title = QCheckBox("Title", g_data_fixer_group)
		self.g_data_fixer_artist = QCheckBox("Artist", g_data_fixer_group)
		g_data_fixer_options.addWidget(self.g_data_fixer_title)
		g_data_fixer_options.addWidget(self.g_data_fixer_artist)

		# Advanced / Database
		advanced_db_page, advanced_db_page_l = new_tab('Database', advanced)
		# Advanced / Database / Import/Export
		def init_export():
			confirm_msg = QMessageBox(QMessageBox.Question, '', 'Are you sure you want to export your database? This might take a long time.',
							 QMessageBox.Yes | QMessageBox.No, self)
			if confirm_msg.exec() == QMessageBox.Yes:
				app_popup = ApplicationPopup(self.parent_widget)
				app_popup.info_lbl.setText("Exporting database...")
				app_popup.export_instance = io_misc.ImportExport()
				app_popup.export_instance.moveToThread(app_constants.GENERAL_THREAD)
				app_popup.export_instance.finished.connect(app_popup.export_instance.deleteLater)
				app_popup.export_instance.finished.connect(app_popup.close)
				app_popup.export_instance.amount.connect(app_popup.prog.setMaximum)
				app_popup.export_instance.progress.connect(app_popup.prog.setValue)
				self.init_gallery_eximport.connect(app_popup.export_instance.export_data)
				self.init_gallery_eximport.emit(None)
				app_popup.adjustSize()
				app_popup.show()
				self.close()

		def init_import():
			path = QFileDialog.getOpenFileName(self,
									  'Choose happypanda database file', filter='*.hpdb')
			path = path[0]
			if len(path) != 0:
				app_popup = ApplicationPopup(self.parent_widget)
				app_popup.restart_info.hide()
				app_popup.info_lbl.setText("Importing database file...")
				app_popup.note_info.setText("Application requires a restart after importing")
				app_popup.import_instance = io_misc.ImportExport()
				app_popup.import_instance.moveToThread(app_constants.GENERAL_THREAD)
				app_popup.import_instance.finished.connect(app_popup.import_instance.deleteLater)
				app_popup.import_instance.finished.connect(app_popup.init_restart)
				app_popup.import_instance.amount.connect(app_popup.prog.setMaximum)
				app_popup.import_instance.imported_g.connect(app_popup.info_lbl.setText)
				app_popup.import_instance.progress.connect(app_popup.prog.setValue)
				self.init_gallery_eximport.connect(app_popup.import_instance.import_data)
				self.init_gallery_eximport.emit(path)
				app_popup.adjustSize()
				app_popup.show()
				self.close()

		advanced_impexp, advanced_impexp_l = groupbox('Import/Export', QFormLayout, advanced_db_page)
		advanced_db_page_l.addRow(advanced_impexp)
		self.export_format = QComboBox(advanced_db_page)
		#self.export_format.addItem('Text File', 0)
		self.export_format.addItem('HPDB', 1)
		self.export_format.adjustSize()
		self.export_format.setFixedWidth(self.export_format.width())
		advanced_impexp_l.addRow('Export Format:', self.export_format)
		self.export_path = PathLineEdit(advanced_impexp, filters='')
		advanced_impexp_l.addRow('Export Path:', self.export_path)
		import_btn = QPushButton('Import database')
		import_btn.clicked.connect(init_import)
		export_btn = QPushButton('Export database')
		export_btn.clicked.connect(init_export)
		ex_imp_btn_l = QHBoxLayout()
		ex_imp_btn_l.addWidget(import_btn)
		ex_imp_btn_l.addWidget(export_btn)
		advanced_impexp_l.addRow(ex_imp_btn_l)


		# About
		about = QTabWidget(self)
		self.about_index = self.right_panel.addWidget(about)
		about_happypanda_page, about_layout = new_tab("About Happypanda", about, False)
		info_lbl = QLabel(app_constants.ABOUT)
		info_lbl.setWordWrap(True)
		info_lbl.setOpenExternalLinks(True)
		about_layout.addWidget(info_lbl)
		about_layout.addWidget(Spacer('v'))
		open_hp_folder = QPushButton('Open Happypanda Directory')
		open_hp_folder.clicked.connect(self.open_hp_folder)
		open_hp_folder.adjustSize()
		open_hp_folder.setFixedWidth(open_hp_folder.width())
		about_layout.addWidget(open_hp_folder)

		# About / DB Overview
		about_db_overview, about_db_overview_m_l = new_tab('DB Overview', about)
		about_stats_tab_widget = misc_db.DBOverview(self.parent_widget)
		about_db_overview_options = QHBoxLayout()
		self.tags_treeview_on_start = QCheckBox('Start with application', about_db_overview)
		make_window_btn = QPushButton('Open in window', about_db_overview)
		make_window_btn.adjustSize()
		make_window_btn.setFixedWidth(make_window_btn.width())
		about_db_overview_options.addWidget(self.tags_treeview_on_start)
		about_db_overview_options.addWidget(make_window_btn)
		def mk_btn_false():
			try:
				make_window_btn.setDisabled(False)
			except RuntimeError:
				pass
		def make_tags_treeview_window():
			self.parent_widget.tags_treeview = misc_db.DBOverview(self.parent_widget, True)
			self.parent_widget.tags_treeview.about_to_close.connect(mk_btn_false)
			make_window_btn.setDisabled(True)
			self.parent_widget.tags_treeview.show()
		if self.parent_widget.tags_treeview:
			self.parent_widget.tags_treeview.about_to_close.connect(mk_btn_false)
			make_window_btn.setDisabled(True)
		make_window_btn.clicked.connect(make_tags_treeview_window)
		about_db_overview_m_l.addRow(about_db_overview_options)
		about_db_overview_m_l.addRow(about_stats_tab_widget)

		# About / Troubleshooting
		about_troubleshoot_page = QWidget()
		about.addTab(about_troubleshoot_page, 'Bug Reporting')
		troubleshoot_layout = QVBoxLayout()
		about_troubleshoot_page.setLayout(troubleshoot_layout)
		guide_lbl = QLabel(app_constants.TROUBLE_GUIDE)
		guide_lbl.setTextFormat(Qt.RichText)
		guide_lbl.setOpenExternalLinks(True)
		guide_lbl.setWordWrap(True)
		troubleshoot_layout.addWidget(guide_lbl, 0, Qt.AlignTop)
		troubleshoot_layout.addWidget(Spacer('v'))

		# About / Search tutorial
		about_search_tut, about_search_tut_l = new_tab("Search Guide", about, True)
		g_search_lbl = QLabel(app_constants.SEARCH_TUTORIAL_TAGS)
		g_search_lbl.setWordWrap(True)
		about_search_tut_l.addRow(g_search_lbl)

		# About / Regex Cheatsheet
		about_s_regex, about_s_regex_l = new_tab("Regex Cheatsheet", about, True)
		reg_info = QLabel(app_constants.REGEXCHEAT)
		reg_info.setWordWrap(True)
		about_s_regex_l.addRow(reg_info)

	def add_folder_monitor(self, path=''):
		if not isinstance(path, str):
			path = ''
		l_edit = PathLineEdit()
		l_edit.setText(path)
		n = self.folders_layout.rowCount() + 1
		self.folders_layout.addRow('{}'.format(n), l_edit)

	def add_ignore_path(self, path='', dir=True):
		if not isinstance(path, str):
			path = ''
		l_edit = PathLineEdit(dir=dir)
		l_edit.setText(path)
		n = self.ignore_path_l.rowCount() + 1
		self.ignore_path_l.addRow('{}'.format(n), l_edit)

	def color_checker(self, txt):
		allow = False
		if len(txt) == 7:
			if txt[0] == '#':
				allow = True
		return allow

	def take_all_layout_widgets(self, l):
		n = l.rowCount()
		items = []
		for x in range(n):
			item = l.takeAt(x+1)
			items.append(item.widget())
		return items


	def choose_font(self):
		tup = QFontDialog.getFont(self)
		font = tup[0]
		if tup[1]:
			self.font_lbl.setText(font.family())
			self.font_size_lbl.setValue(font.pointSize())

	def open_hp_folder(self):
		if os.name == 'posix':
			utils.open_path(app_constants.posix_program_dir)
		else:
			utils.open_path(os.getcwd())

	def reject(self):
		self.close()
Example #6
0
class TextBoxDropDownWidget(CustomBaseWidget):
    i = 0.0

    def __init__(self, tab, name, x, y, widgetInfo):
        self.textBoxWidget = QLabel()
        self.dropDownWidget = QComboBox()

        super().__init__(QWidget(tab, objectName=name),
                         x,
                         y,
                         configInfo=widgetInfo,
                         widgetType=Constants.DROP_DOWN_TEXT_BOX_TYPE)

        layout = QGridLayout()
        layout.addWidget(self.dropDownWidget)
        layout.addWidget(self.textBoxWidget)
        self.QTWidget.setLayout(layout)

        self.xBuffer = 0
        self.yBuffer = 0

        self.source = "_"
        if widgetInfo is not None:
            if Constants.SOURCE_ATTRIBUTE in widgetInfo:
                self.source = widgetInfo[Constants.SOURCE_ATTRIBUTE]

        self.menuItems = []
        self.setMenuItems(["No data"])

    def customUpdate(self, dataPassDict):
        if self.source not in dataPassDict:
            self.textBoxWidget.setText("No Data")
            return
        dataStruct = dataPassDict[self.source]

        selectedTarget = self.dropDownWidget.currentText()
        menuItems = []
        for item in dataStruct:
            menuItems.append(item)
        self.setMenuItems(menuItems)

        if selectedTarget not in dataStruct:
            return
        dataToPrint = dataStruct[selectedTarget]

        outString = ""
        longestLine = 0
        for line in dataToPrint:
            line[0] = line[0].replace("\t", "     ").rstrip(
            )  # Do some formatting to convert tabs to spaces and ditch trailing spaces
            longestLine = max(longestLine, len(line[0]))

        for line in dataToPrint:
            spaces = " " * (longestLine - len(line[0]) + 2
                            )  # Add two extra spaces to everything
            newLine = "{0}{2}{1}\n".format(line[0],
                                           str(line[1]).lstrip(), spaces)

            outString = outString + newLine

        outString = outString[:-1]  # Remove last character

        self.textBoxWidget.setText(outString)
        self.QTWidget.adjustSize()

    def setMenuItems(self, menuItemList):
        if menuItemList != self.menuItems:
            self.dropDownWidget.clear()
            self.dropDownWidget.addItems(menuItemList)
        self.menuItems = menuItemList

    def setColorRGB(self, red, green, blue):
        colorString = "background: rgb({0}, {1}, {2});".format(
            red, green, blue)

        self.QTWidget.setStyleSheet("QWidget#" + self.QTWidget.objectName() +
                                    " {border: 1px solid " + self.borderColor +
                                    "; " + colorString + " color: " +
                                    self.textColor + "}")
        self.textBoxWidget.setStyleSheet(colorString + " color: " +
                                         self.textColor)
        self.dropDownWidget.setStyleSheet(colorString + " color: " +
                                          self.headerTextColor)

    def setDefaultAppearance(self):
        self.QTWidget.setStyleSheet("color: black")
        self.textBoxWidget.setStyleSheet("color: black")
        self.dropDownWidget.setStyleSheet("color: black")

    def setFontInfo(self):
        self.QTWidget.setFont(QFont(self.font, self.fontSize))
        self.dropDownWidget.setFont(QFont(self.font, self.fontSize))
        self.textBoxWidget.setFont(QFont("Monospace", self.fontSize))
        self.dropDownWidget.adjustSize()
        self.QTWidget.adjustSize()

    def customXMLStuff(self, tag):
        tag.set(Constants.SOURCE_ATTRIBUTE, str(self.source))
Example #7
0
class Finance_Passion_Interface:
   def __init__(self,file):
      self.window(file)
   def window(self,file):
      self.app = QApplication(sys.argv)
      self.win = QWidget()
      self.e1 = erd(file)
      self.e2=self.e1.get_category()
      self.combo1 = QComboBox(self.win)
      self.combo1.addItem("Select Category")
      for i in self.e2:
         self.combo1.addItem(i)
      self.combo1.move(80,25)
      self.label1 = QLabel(self.win)
      self.label1.move(25, 25)
      self.label2 = QLabel(self.win)
      self.label2.move(25, 50)
      self.label2.setText("Total Current Value:")
      self.label21 = QLabel(self.win)
      self.label21.move(230, 50)
      self.label21.setText("Total Monthly Installment Amount:")
      self.label22 = QLabel(self.win)
      self.label22.move(425,50)
      self.label22.setText(str(self.e1.get_total_installment_value()))
      self.label3=QLabel(self.win)
      self.label3.move(180, 50)
      self.label3.setText(str(self.e1.get_total_current_value()))
      self.label3.adjustSize()
      self.label4 = QLabel(self.win)
      self.label4.move(200,25)
      self.label5 = QLabel(self.win)
      self.label5.move(2, 75)
      self.label5.setText("---------------------------------------------------------------------------------------------------------------------------")
      self.label6 = QLabel(self.win)
      self.label6.move(25, 85)
      self.label6.setText("Account Details")
      self.label1.setText("Category")
      self.label7 = QLabel(self.win)
      self.label7.move(2, 95)
      self.label7.setText("---------------------------------------------------------------------------------------------------------------------------")
      self.label5.hide()
      self.label6.hide()
      self.label7.hide()
      self.label8 = QLabel(self.win)
      self.label8.move(25,110)
      self.label8.setText("Account #:")
      self.label8.hide()
      self.label9 = QLabel(self.win)
      self.label9.move(80, 110)
      self.label9.setText("")
      self.label9.hide()
      self.label10 = QLabel(self.win)
      self.label10.setText("Installement Amount:")
      self.label10.move(175,110)
      self.label10.hide()
      self.label11 = QLabel(self.win)
      self.label11.move(280, 110)
      self.label11.setText("")
      self.label11.hide()
      self.label12 = QLabel(self.win)
      self.label12.move(25,130)
      self.label12.setText("Remaining Installement:")
      self.label12.hide()
      self.label13 = QLabel(self.win)
      self.label13.move(145, 130)
      self.label13.setText("")
      self.label13.hide()
      self.label14 = QLabel(self.win)
      self.label14.move(325, 110)
      self.label14.setText("Maturity Amount:")
      self.label14.hide()
      self.label15 = QLabel(self.win)
      self.label15.move(410, 110)
      self.label15.setText("")
      self.label15.hide()
      self.label16 = QLabel(self.win)
      self.label16.move(175, 130)
      self.label16.setText("Start Date:")
      self.label16.hide()
      self.label17 = QLabel(self.win)
      self.label17.move(235, 130)
      self.label17.setText("")
      self.label17.hide()
      self.label18 = QLabel(self.win)
      self.label18.move(325, 130)
      self.label18.setText("Maturity Date:")
      self.label18.hide()
      self.label19 = QLabel(self.win)
      self.label19.move(400, 130)
      self.label19.setText("")
      self.label19.hide()
      self.combo1.activated[str].connect(self.catChanged)
      self.combo2 = QComboBox(self.win)
      self.combo2.move(350,25)
      self.combo2.hide()
      self.combo2.activated[str].connect(self.acctChanged)

      self.m=[]
      self.m.append()
      self.E=[]
      self.expl=[]
      for i in self.e2:
         e3=self.e1.get_current_value_by_category(i)
         self.E.append(e3)
         self.expl.append(0)
      self.m=MultiCanvas(self.win, width=5, height=4,list1=self.e2,list2=self.E,list3=self.expl)
      self.m.move(2,175)

      self.win.setGeometry(50, 50, 500, 600)
      self.win.setWindowTitle("Finance Passion")
      self.win.show()
      sys.exit(self.app.exec_())

   def catChanged(self, text):
      self.label5.hide()
      self.label6.hide()
      self.label7.hide()
      self.label8.hide()
      self.label9.hide()
      self.label10.hide()
      self.label11.hide()
      self.label12.hide()
      self.label13.hide()
      self.label14.hide()
      self.label15.hide()
      self.label16.hide()
      self.label17.hide()
      self.label18.hide()
      self.label19.hide()
      if(text=="Select Category"):
         self.label2.setText("Total Current Value:")
         self.label2.adjustSize()
         self.label21.setText("Total Monthly Installment:")
         self.label4.setText("")
         self.combo2.hide()
         self.combo2.clear()
         expl=[0 for i in range(len(self.m.lab))]
         self.m.graph_clear()
         self.m.pie_plot(expl)
         self.m.move(2, 175)
      else:
         self.label2.setText("Total "+text+" current value")
         self.label21.setText("Total "+text+" Monthly Installment :")
         self.label4.setText(text+" Account List:")
         self.combo2.clear()
         self.combo2.show()
         self.m.graph_clear()
         expl=[]
         for i in self.e1.get_category():
            if(i==text):
               expl.append(0.1)
            else:
               expl.append(0)
         del self.m
         self.m = MultiCanvas(self.win, width=5, height=4, list1=self.e2, list2=self.E, list3=self.expl)
         self.m.move(2, 175)
         e3=self.e1.get_account_list_by_category(text)
         self.combo2.addItem("Account List")
         for i in e3:
            self.combo2.addItem(i)
         self.combo2.adjustSize()
      self.label2.adjustSize()
      self.label4.adjustSize()
      self.label21.adjustSize()
      if (text == "Select Category"):
         self.label3.setText(str(self.e1.get_total_current_value()))
         self.label22.setText(str(self.e1.get_total_installment_value()))
      else:
         self.label3.setText(str(self.e1.get_current_value_by_category(text)))
         self.label22.setText(str(self.e1.get_installement_value_by_category(text)))
      self.label3.adjustSize()
      self.label22.adjustSize()

   def acctChanged(self,acct):
      self.label5.show()
      self.label6.show()
      self.label7.show()
      self.label8.show()
      self.label9.show()
      self.label10.show()
      self.label11.show()
      self.label12.show()
      self.label13.show()
      self.label14.show()
      self.label15.show()
      self.label16.show()
      self.label17.show()
      self.label18.show()
      self.label19.show()
      if (acct == "Account List"):
         self.label5.hide()
         self.label6.hide()
         self.label7.hide()
         self.label8.hide()
         self.label9.hide()
         self.label10.hide()
         self.label11.hide()
         self.label12.hide()
         self.label13.hide()
         self.label14.hide()
         self.label15.hide()
         self.label16.hide()
         self.label17.hide()
         self.label18.hide()
         self.label19.hide()
      else:
         self.label9.setText(acct)
         self.label9.adjustSize()
         self.label11.setText(str(self.e1.get_amount_by_account(acct)))
         self.label11.adjustSize()
         self.label13.setText(str(self.e1.get_remaining_by_account(acct)))
         self.label13.adjustSize()
         self.label15.setText(str(self.e1.get_maturity_amount_by_account(acct)))
         self.label15.adjustSize()
         self.label17.setText(str(self.e1.get_start_date_by_account(acct)))
         self.label17.adjustSize()
         self.label19.setText(str(self.e1.get_maturity_date_by_account(acct)))
         self.label19.adjustSize()
    def build_detailbox(self):

        box = QGridLayout()
        table = self.mainwindow.table_selected
        # print(f"table = {table}")

        recordarray = self.mainwindow.record_selected.recordarray
        # print(f"recordarray = {recordarray}")

        for index, columntype in enumerate(table.column_types):

            columnname = table.column_names[index]

            # set title for widget
            widget_title = QLabel()
            widget_title.setText(columnname)

            # check if column is a foreign key, it needs at least 3 text fields between spaces (column name, fk denotion, fk column)
            fkfound = False
            # print(f"columntype.upper = {columntype.upper()}")
            if "REFERENCES" in columntype.upper():
                fkfound = True
                print(
                    f"index {index} and recordarray {recordarray}, found foreign key {columntype}"
                )
                widget_value = QComboBox()

                # get the actual records of the foreign table
                foreign_records = self.mainwindow.handler.table_get_foreign_records(
                    tablename=table.name, column=columnname)

                # Create first row for a no choice option
                widget_value.addItem(f"No {columnname}", 0)

                # get the id and name column of the foreign records
                for record_index, foreign_record in enumerate(foreign_records):
                    foreign_id = foreign_record.primarykey
                    foreign_name = foreign_record.recorddict["name"]

                    # add item with both a shown string (1) as well as a piece of data (2)
                    widget_value.addItem(foreign_name, foreign_id)

                    # below sets itemdata at a certain point (1), data itself (2) and what its used for (3)
                    # including the no choice, the actual combo index is plus 1
                    widget_tooltip = f"tooltip {foreign_name}"
                    widget_value.setItemData(record_index + 1, widget_tooltip,
                                             Qt.ToolTipRole)
                    # print(f"added {foreign_name} with {foreign_id}")

                    if recordarray[index] == foreign_id:
                        # setting the default value and the tooltip for the combobox itself
                        # print(f"record shows value {recordarray[index]}")
                        widget_value.setCurrentIndex(record_index + 1)
                        widget_value.setToolTip(widget_tooltip)

            # if fkfound is true then it was a foreign key and the widget is already made
            if fkfound == False:
                ctype = columntype.split(' ', 1)[0].upper()
                # print(f"ctype = {ctype}")
                print(f"index {index} and recordarray {recordarray}")
                if ctype == "INTEGER":
                    widget_value = QSpinBox()
                    widget_value.setMinimum(-1)
                    widget_value.setValue(recordarray[index])

                elif ctype == "BOOL":
                    widget_value = QCheckBox()
                    widget_value.setChecked(recordarray[index])

                elif ctype == "VARCHAR(255)":
                    widget_value = QLineEdit()
                    widget_value.setText(recordarray[index])

                elif ctype == "TEXT":
                    widget_value = QTextEdit()
                    widget_value.adjustSize()
                    widget_value.insertPlainText(recordarray[index])
                    # widget_value.insertHtml(recordarray[index])

                # elif ctype == "DATE":
                #     widget_value = QDateEdit()
                #     date = QDate()
                #     sqldate = recordarray[index]
                #     datestring = datetime.date()
                #     date.fromString(recordarray[index], 'yyyy-MM-dd')
                #     widget_value.setDate(date)

                # elif ctype == "DATETIME" or ctype == "TIMESTAMP":
                #     widget_value = QDateTimeEdit()
                #     date = QDateTime()
                #     sqldate = recordarray[index]
                #     datestring = datetime.datetime()
                #     date.fromString(recordarray[index], 'yyyy-MM-dd')
                #     widget_value.setDate(date)

                else:
                    try:
                        # assumed text
                        widget_value = QLineEdit()
                        widget_value.setText(recordarray[index])
                    except:
                        widget_value = QLineEdit()
                        widget_value.setText("Error setting widget")

                # set focus if widget is "name"
                if table.column_names[index] == "name":
                    widget_value.setFocusPolicy(Qt.StrongFocus)

            # print(f"column placements are {table.column_placements}")
            # print(f"column placements[index] are {table.column_placements[index]}")
            row = table.column_placements[index][0]
            column = table.column_placements[index][1] + 1
            heigth = table.column_placements[index][2]
            width = table.column_placements[index][3]

            # add widget and title to the layout
            box.addWidget(widget_value, row, column, heigth, width)
            box.addWidget(widget_title, row, 0, heigth, 1)

            # add the value widget to the list of widgets for easy access of values
            self.widgets.append(widget_value)

        # finish  window
        frame = QFrame()
        frame.setLayout(box)
        self.addWidget(frame, 0, 0, 2, 8)
Example #9
0
class Dataset(QFrame):
    default_text = "<i>Please select a file.<\i>"
    download_text = "Download"
    downloading_text = "Downloading..."

    def __init__(self, app):
        super().__init__()
        # initialize our variables
        self.app = app
        self.file = None
        self.init_ui()

    def init_ui(self):
        # make our UI
        self.setObjectName("content")
        layout = QHBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)

        # our main content area
        content = QFrame()
        content_layout = QVBoxLayout()

        # some info
        title = QLabel("Dataset")
        title.setObjectName("h1")
        description = QLabel(
            "Download images from URLs in a .csv or .xlsx file.\nOptionally, supply labels to organize your images into folders by label."
        )
        description.setObjectName("h2")

        # file selection button
        self.file_button = QPushButton("Select file")
        self.file_button.clicked.connect(self.select_file)
        button_container = NoStretch(self.file_button)
        button_container.setObjectName("separate")

        # display filepath
        self.path_label = QLabel(self.default_text)

        # url column header and optional label column header
        self.header_container = QFrame()
        self.header_container.setObjectName("separateSmall")
        header_layout = QVBoxLayout()
        header_layout.setContentsMargins(0, 0, 0, 0)
        url_label = QLabel("Column with image URLs:")
        self.url_dropdown = QComboBox()
        self.url_dropdown.setSizeAdjustPolicy(QComboBox.AdjustToContents)
        self.url_dropdown.setSizePolicy(QSizePolicy.Preferred,
                                        QSizePolicy.Expanding)
        url_container = NoStretch(self.url_dropdown)
        label_label = QLabel("(Optional) column with labels:")
        label_label.setObjectName("separateSmall")
        self.label_dropdown = QComboBox()
        self.label_dropdown.setSizeAdjustPolicy(QComboBox.AdjustToContents)
        self.label_dropdown.setSizePolicy(QSizePolicy.Preferred,
                                          QSizePolicy.Expanding)
        label_container = NoStretch(self.label_dropdown)
        header_layout.addWidget(url_label)
        header_layout.addWidget(url_container)
        header_layout.addWidget(label_label)
        header_layout.addWidget(label_container)
        self.header_container.setLayout(header_layout)
        self.header_container.hide()

        # download button
        self.download_button = QPushButton(self.download_text)
        self.download_button.setEnabled(False)
        self.download_button.clicked.connect(self.download)
        download_container = NoStretch(self.download_button)
        download_container.setObjectName("separate")

        self.progress_bar = QProgressBar()
        self.progress_bar.hide()

        # make our content layout
        content_layout.addWidget(title)
        content_layout.addWidget(description)
        content_layout.addWidget(button_container)
        content_layout.addWidget(self.path_label)
        content_layout.addWidget(self.header_container)
        content_layout.addWidget(download_container)
        content_layout.addWidget(self.progress_bar)
        content_layout.addStretch(1)
        content.setLayout(content_layout)

        layout.addWidget(content)
        layout.addStretch(1)
        self.setLayout(layout)

    def select_file(self):
        self.file = QFileDialog.getOpenFileName(self,
                                                'Select CSV File',
                                                filter="CSV (*.csv *.xlsx)")[0]
        self.path_label.setText(
            f"<i>{self.file}</i>" if self.file else self.default_text)
        self.parse_headers()

    def parse_headers(self):
        if self.file:
            # read the file for its headers and set our dropdown boxes appropriately
            try:
                if os.path.splitext(self.file)[1] == ".csv":
                    csv = pd.read_csv(self.file, header=0)
                else:
                    csv = pd.read_excel(self.file, header=0)
                self.label_dropdown.clear()
                self.url_dropdown.clear()
                self.label_dropdown.addItem(None)
                for header in list(csv.columns):
                    self.url_dropdown.addItem(header)
                    self.label_dropdown.addItem(header)
                self.url_dropdown.adjustSize()
                self.header_container.show()
                self.download_button.setEnabled(True)
            except Exception as e:
                QMessageBox.about(self, "Alert", f"Error reading csv: {e}")
                self.clear_headers()
        else:
            self.clear_headers()

    def clear_headers(self):
        self.header_container.hide()
        self.url_dropdown.clear()
        self.label_dropdown.clear()
        self.download_button.setEnabled(False)

    def download(self):
        # disable the buttons so we can't click again
        self.download_button.setEnabled(False)
        self.download_button.setText(self.downloading_text)
        self.file_button.setEnabled(False)
        self.progress_bar.setValue(0)
        self.progress_bar.show()
        self.app.processEvents()
        url_col = self.url_dropdown.currentText()
        label_col = self.label_dropdown.currentText()
        destination_directory = QFileDialog.getExistingDirectory(
            self, "Select Output Directory")
        # if they hit cancel, don't download
        if not destination_directory:
            self.done()
            return
        # otherwise try downloading to the desired location
        try:
            create_dataset(
                filepath=self.file,
                url_col=url_col,
                label_col=label_col if label_col else None,
                progress_hook=self.progress_hook,
                destination_directory=destination_directory,
            )
        except Exception as e:
            QMessageBox.about(self, "Alert", f"Error creating dataset: {e}")
            self.done()

    def progress_hook(self, current, total):
        self.progress_bar.setValue(float(current) / total * 100)
        if current == total:
            self.done()
        # make sure to update the UI
        self.app.processEvents()

    def done(self):
        self.progress_bar.setValue(0)
        self.progress_bar.hide()
        self.download_button.setEnabled(True)
        self.download_button.setText(self.download_text)
        self.file_button.setEnabled(True)
        self.app.processEvents()
class App(QMainWindow):
    send_to_generator = pyqtSignal(str, tuple, str, str, str)

    def __init__(self):
        super().__init__()
        self.title = "Generator Holzworth"
        self.left = 30
        self.top = 30
        self.width = 720
        self.height = 500
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        # get available ports on start
        self.available_ports = genserialport.list_ports()
        # combo for choose appropriate port
        self.port_select = QComboBox(self)
        self.port_select.addItems(self.available_ports)
        self.port_select.move(550, 400)
        self.port_select.adjustSize()
        # LCDs and labels for frequency, power and phase settings
        self.lcd_frequency_channel1 = QLCDNumber(self)
        self.lcd_frequency_channel1.move(20, 30)
        self.lcd_frequency_channel1.resize(260, 50)
        self.lcd_frequency_channel1.display(100.0)
        self.lcd_frequency_channel1.setDigitCount(11)

        self.channel1_mhz_label = QLabel("MHz", self)
        self.channel1_mhz_label.move(285, 40)
        self.channel1_mhz_label.setFont(QFont("Times", 20))

        self.lcd_power_channel1 = QLCDNumber(self)
        self.lcd_power_channel1.move(350, 30)
        self.lcd_power_channel1.resize(100, 50)
        self.lcd_power_channel1.display(0.0)

        ch1_dbm_label = QLabel("dBm", self)
        ch1_dbm_label.move(455, 40)
        ch1_dbm_label.setFont(QFont("Times", 20))

        self.lcd_phase_channel1 = QLCDNumber(self)
        self.lcd_phase_channel1.move(525, 30)
        self.lcd_phase_channel1.resize(100, 50)
        self.lcd_phase_channel1.display(0.0)

        ch1_degree_label = QLabel(u"°", self)
        ch1_degree_label.move(630, 30)
        ch1_degree_label.setFont(QFont("Times", 20))
        # checkbox to choose channel
        self.label_channel1 = QLabel(u"Kanał 1", self)
        self.label_channel1.move(20, 5)

        self.label_channel2 = QLabel(u"Kanał 2", self)
        self.label_channel2.move(20, 95)

        self.checkbox_channel1 = QCheckBox(u"Kanał 1", self)
        self.checkbox_channel1.move(20, 300)

        self.checkbox_channel2 = QCheckBox(u"Kanał 2", self)
        self.checkbox_channel2.move(20, 330)
        #LCDs and labels for second channel
        self.lcd_frequency_channel2 = QLCDNumber(self)
        self.lcd_frequency_channel2.move(20, 120)
        self.lcd_frequency_channel2.resize(260, 50)
        self.lcd_frequency_channel2.display(100.0)
        self.lcd_frequency_channel2.setDigitCount(11)

        self.f2_label = QLabel("MHz", self)
        self.f2_label.move(285, 130)
        self.f2_label.setFont(QFont("Times", 20))

        self.lcd_power_channel2 = QLCDNumber(self)
        self.lcd_power_channel2.move(350, 120)
        self.lcd_power_channel2.resize(100, 50)
        self.lcd_power_channel2.display(0.0)

        ch2_dbm_label = QLabel("dBm", self)
        ch2_dbm_label.move(455, 130)
        ch2_dbm_label.setFont(QFont("Times", 20))

        self.lcd_phase_channel2 = QLCDNumber(self)
        self.lcd_phase_channel2.move(525, 120)
        self.lcd_phase_channel2.resize(100, 50)
        self.lcd_phase_channel2.display(0.0)

        ch2_degree_label = QLabel(u"°", self)
        ch2_degree_label.move(630, 120)
        ch2_degree_label.setFont(QFont("Times", 20))
        # textbox to edit to set generator parameters
        self.textbox_frequency_set = QLineEdit(self)
        self.textbox_frequency_set.move(20, 220)
        self.textbox_frequency_set.resize(200, 40)

        self.textbox_power_set = QLineEdit(self)
        self.textbox_power_set.move(350, 220)
        self.textbox_power_set.resize(100, 40)

        label_frequency = QLabel(u"Częstotliwość", self)
        label_frequency.move(20, 195)
        label_frequency.adjustSize()

        label_power = QLabel("Moc", self)
        label_power.move(350, 195)

        label_dbm = QLabel("dBm", self)
        label_dbm.move(455, 220)

        label_phase = QLabel(u"Przesunięcie fazy", self)
        label_phase.move(525, 195)
        label_phase.adjustSize()

        self.textbox_phase_set = QLineEdit(self)
        self.textbox_phase_set.move(525, 220)
        self.textbox_phase_set.resize(100, 40)

        label_Hz = QLabel("Hz", self)
        label_Hz.move(230, 220)
        # regular expression for settings
        reg_exp_freq = QRegExp(
            "[0-9]{0,4}[.]{0,1}[0-9]{0,6}[kMG]"
        )  # 4 digits before dot, 6 after, must end with k,M or G
        gen_validator = QRegExpValidator(reg_exp_freq,
                                         self.textbox_frequency_set)
        self.textbox_frequency_set.setValidator(gen_validator)
        # regex for power settings
        reg_exp_power = QRegExp("[-]*[0-9]+[.]*[0-9]{2}")
        gen_validator = QRegExpValidator(reg_exp_power, self.textbox_power_set)
        self.textbox_power_set.setValidator(gen_validator)
        # regex for phase settings
        phase_validator = QRegExpValidator(QRegExp("[0-9]+[.]*[0-9]"),
                                           self.textbox_phase_set)
        self.textbox_phase_set.setValidator(phase_validator)
        # button for refresh available serial ports
        self.ports_button = QPushButton(u"Odśwież porty", self)
        self.ports_button.move(400, 400)
        self.ports_button.clicked.connect(self.refresh_ports)
        self.ports_button.adjustSize()
        # button to set generator
        self.activate_button = QPushButton("Ustaw", self)
        self.activate_button.move(300, 400)
        # thread creation and signals and slots connection
        self.generator_thread = QThread()
        self.generator_worker = GeneratorWorker()
        self.generator_worker.moveToThread(self.generator_thread)
        self.activate_button.clicked.connect(
            self.get_user_input_and_send_to_generator)
        self.send_to_generator.connect(
            self.generator_worker.send_settings_to_generator)
        self.generator_worker.set_display.connect(self.show_on_display)
        self.generator_worker.event_occured.connect(self.show_event)
        self.generator_thread.start()

        self.show()

    def show_on_display(self, setting: str):
        if setting == "frequency":
            user_freq_set = self.textbox_frequency_set.text()
            self.lcd_frequency_channel2.display(
                user_freq_set[0:len(user_freq_set) - 1])
            self.f2_label.setText(
                GeneratorWorker.freq_dict[user_freq_set[len(user_freq_set) -
                                                        1]])
        elif setting == "power":
            self.lcd_power_channel2.display(self.textbox_power_set.text())
        elif setting == "phase":
            self.lcd_phase_channel2.display(self.textbox_phase_set.text())

    def show_event(self, message):
        QMessageBox.about(self, "Komunikat", message)

    def get_user_input_and_send_to_generator(self):
        user_freq = self.textbox_frequency_set.text()
        user_pwr = self.textbox_power_set.text()
        user_ph = self.textbox_phase_set.text()
        current_port = str(self.port_select.currentText())
        active_channels = (self.checkbox_channel1.isChecked(),
                           self.checkbox_channel2.isChecked())
        self.send_to_generator.emit(current_port, active_channels, user_freq,
                                    user_pwr, user_ph)

    def refresh_ports(self):
        self.port_select.clear()
        self.port_select.addItems(genserialport.list_ports())
Example #11
0
class Model(QFrame):
    default_model_text = "<i>Please select a TensorFlow model directory.<\i>"
    default_file_text = "<i>Please select a folder of images or a csv of URLs.<\i>"
    predict_text = "Predict"
    predicting_text = "Predicting..."

    def __init__(self, app):
        super().__init__()
        # initialize our variables
        self.app = app
        self.tf_directory = None
        self.file = None
        self.folder = None
        self.init_ui()

    def init_ui(self):
        # make our UI
        self.setObjectName("content")
        layout = QHBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)

        # our main content area
        content = QFrame()
        content_layout = QVBoxLayout()

        # some info
        title = QLabel("Model")
        title.setObjectName("h1")
        description = QLabel(
            "Run your exported TensorFlow model from Lobe \non a folder of images or a .csv/.xlsx file of image URLs.\nThis will produce a new prediction .csv with the image filepath or URL, \nthe model's prediction, and the model's confidence."
        )
        description.setObjectName("h2")

        # model select button
        self.model_button = QPushButton("Select model directory")
        self.model_button.clicked.connect(self.select_directory)
        model_container = NoStretch(self.model_button)
        model_container.setObjectName("separate")
        self.model_label = QLabel(self.default_model_text)

        # file or folder selection button
        self.folder_button = QPushButton("Select folder")
        self.folder_button.clicked.connect(self.select_image_folder)
        self.file_button = QPushButton("Select file")
        self.file_button.clicked.connect(self.select_file)
        buttons_container = NoStretch([self.folder_button, self.file_button])
        buttons_container.setObjectName("separate")
        self.path_label = QLabel(self.default_file_text)

        # url column header
        self.url_label = QLabel("Column with image URLs:")
        self.url_label.setObjectName("separateSmall")
        self.url_label.hide()
        self.url_dropdown = QComboBox()
        self.url_dropdown.setSizeAdjustPolicy(QComboBox.AdjustToContents)
        self.url_dropdown.setSizePolicy(QSizePolicy.Preferred,
                                        QSizePolicy.Expanding)
        self.url_container = NoStretch(self.url_dropdown)
        self.url_container.hide()

        # predict button
        self.predict_button = QPushButton(self.predict_text)
        self.predict_button.setEnabled(False)
        self.predict_button.clicked.connect(self.predict)
        predict_container = NoStretch(self.predict_button)
        predict_container.setObjectName("separate")

        self.progress_bar = QProgressBar()
        self.progress_bar.hide()

        # make our content layout
        content_layout.addWidget(title)
        content_layout.addWidget(description)
        content_layout.addWidget(model_container)
        content_layout.addWidget(self.model_label)
        content_layout.addWidget(buttons_container)
        content_layout.addWidget(self.path_label)
        content_layout.addWidget(self.url_label)
        content_layout.addWidget(self.url_container)
        content_layout.addWidget(predict_container)
        content_layout.addWidget(self.progress_bar)
        content_layout.addStretch(1)
        content.setLayout(content_layout)

        layout.addWidget(content)
        layout.addStretch(1)
        self.setLayout(layout)

    def select_directory(self):
        self.tf_directory = QFileDialog.getExistingDirectory(
            self, "Select TensorFlow Model Directory")
        self.model_label.setText(f"<i>{self.tf_directory}</i>" if self.
                                 tf_directory else self.default_model_text)
        self.check_predict_button()

    def select_file(self):
        self.file = QFileDialog.getOpenFileName(self,
                                                'Select CSV File',
                                                filter="CSV (*.csv *.xlsx)")[0]
        self.path_label.setText(
            f"<i>{self.file}</i>" if self.file else self.default_file_text)
        self.folder = None
        self.parse_headers()
        self.check_predict_button()

    def select_image_folder(self):
        self.folder = QFileDialog.getExistingDirectory(
            self, "Select Images Directory")
        self.path_label.setText(
            f"<i>{self.folder}</i>" if self.folder else self.default_file_text)
        self.file = None
        self.parse_headers()
        self.check_predict_button()

    def check_predict_button(self):
        # enable the button when we have both a model and file
        if self.tf_directory and (self.file or self.folder):
            self.predict_button.setEnabled(True)
        else:
            self.predict_button.setEnabled(False)

    def parse_headers(self):
        if self.file:
            # read the file for its headers and set our dropdown boxes appropriately
            try:
                if os.path.splitext(self.file)[1] == ".csv":
                    csv = pd.read_csv(self.file, header=0)
                else:
                    csv = pd.read_excel(self.file, header=0)
                self.url_dropdown.clear()
                for header in list(csv.columns):
                    self.url_dropdown.addItem(header)
                self.url_dropdown.adjustSize()
                self.url_label.show()
                self.url_container.show()
            except Exception as e:
                QMessageBox.about(self, "Alert", f"Error reading csv: {e}")
                self.clear_headers()
        else:
            self.clear_headers()

    def clear_headers(self):
        self.url_dropdown.clear()
        self.url_label.hide()
        self.url_container.hide()

    def predict(self):
        # disable the buttons so we can't click again
        self.predict_button.setEnabled(False)
        self.predict_button.setText(self.predicting_text)
        self.model_button.setEnabled(False)
        self.file_button.setEnabled(False)
        self.folder_button.setEnabled(False)
        self.progress_bar.setValue(0)
        self.progress_bar.show()
        self.app.processEvents()
        url_col = self.url_dropdown.currentText()
        try:
            if self.file:
                predict_dataset(model_dir=self.tf_directory,
                                filepath=self.file,
                                url_col=url_col,
                                progress_hook=self.progress_hook)
            elif self.folder:
                predict_folder(model_dir=self.tf_directory,
                               img_dir=self.folder,
                               move=True,
                               csv=True,
                               progress_hook=self.progress_hook)
        except Exception as e:
            QMessageBox.about(self, "Alert", f"Error predicting: {e}")
        finally:
            self.done()

    def progress_hook(self, current, total):
        self.progress_bar.setValue(float(current) / total * 100)
        if current == total:
            self.done()
        # make sure to update the UI
        self.app.processEvents()

    def done(self):
        self.progress_bar.setValue(0)
        self.progress_bar.hide()
        self.predict_button.setEnabled(True)
        self.predict_button.setText(self.predict_text)
        self.model_button.setEnabled(True)
        self.file_button.setEnabled(True)
        self.folder_button.setEnabled(True)
        self.app.processEvents()
Example #12
0
class Window(QWidget, calc_new_gui.Ui_AppWindow):
    switch_login = pyqtSignal()

    parameters = ['TRL', 'MRL', 'ERL', 'ORL', 'CRL']

    def __init__(self, user):
        QWidget.__init__(self)
        self.setupUi(self)
        self.setStyleSheet(open(style).read())

        self.tabWidget.setTabEnabled(3, False)
        self.tabWidget.setTabEnabled(4, False)
        self.tabWidget.setTabEnabled(5, False)

        self.expert_name = user
        self.params = []
        self.project_num = ''
        self.rad = []
        self.tprl_min = 0
        self.project_state = ''
        self.label_user_name.setText(user)
        self.label_user_name1.setText(user)
        self.label_user_name2.setText(user)
        self.newproject_data = tuple()
        self.saveproject_data = tuple()
        self.risk_flag = True

        self.btn_set_params.clicked.connect(self.set_params)
        self.btn_calculate.clicked.connect(self.calculate)
        self.btn_reset_tasks.clicked.connect(self.reset_tasks)
        self.btn_help.clicked.connect(self.show_help)
        self.btn_save_results.clicked.connect(self.save_results)
        self.btn_change_user.clicked.connect(self.change_user)
        self.btn_change_user1.clicked.connect(self.change_user)
        self.btn_change_user2.clicked.connect(self.change_user)
        self.btn_load_project.clicked.connect(self.load_project_data)
        self.btn_remove_project.clicked.connect(self.remove_project)
        self.btn_load_project2.clicked.connect(self.load_project_data)
        self.btn_new_project.clicked.connect(self.create_dialog)
        self.tabWidget.currentChanged.connect(self.show_user_projects)
        self.btn_report_ugt.clicked.connect(self.report_ugt)
        # self.btn_report_risks.clicked.connect(self.report_risks)

        self.save_data = pd.DataFrame(
            columns=['Level', 'Pars_Name', 'Task', 'Task_Comments', 'Original_Task', 'State', 'Parameter'])
        # self.normal_risks = {'Ф1': 33, 'Ф2': 62, 'Ф3': 55, 'Ф4': 30, 'Ф5': 28, 'Ф6': 29,
        #                      'Ф7': 69, 'Ф8': 30, 'Ф9': 22, 'Ф10': 19, 'Ф11': 29, 'Ф12': 30,
        #                      'Ф13': 15, 'Ф14': 5, 'Ф15': 9, 'Ф16': 3, 'Ф17': 13, 'Ф18': 14,
        #                      'Ф19': 223}

    @pyqtSlot(int)
    def show_user_projects(self, index):
        if index == 1:
            drafts = check_db.load_project(self.expert_name, 'черновик')
            self.create_table(self.projects_table, drafts)
        elif index == 2:
            complete = check_db.load_project(self.expert_name, 'итог')
            self.create_table(self.projects_table2, complete)
        else:
            pass

    def create_table(self, tab_widget, data):
        tab_widget.setSortingEnabled(False)
        tab_widget.setRowCount(len(data))
        for i in range(len(data)):
            tab_widget.setRowHeight(i, 20)
        for row, form in enumerate(data):
            form = ((str(row + 1)),) + form
            for column, cell in enumerate(form):
                if column == 0:
                    item = QTableWidgetItem(str(row + 1))
                    item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsDragEnabled | Qt.ItemIsEnabled)
                    tab_widget.setColumnWidth(column, 50)
                    item.setTextAlignment(Qt.AlignCenter)
                    tab_widget.setItem(row, column, item)
                else:
                    item = QTableWidgetItem(str(cell))
                    item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsDragEnabled | Qt.ItemIsEnabled)
                    tab_widget.setItem(row, column, item)
        tab_widget.resizeColumnsToContents()
        tab_widget.setColumnWidth(3, 200)
        tab_widget.setSortingEnabled(True)

    def change_user(self):
        self.switch_login.emit()

    def start_project(self, num):
        self.project_num = num
        self.set_param_check(self.parameters, False)
        self.reset_params()
        self.project_state = ''
        temp = []
        for item in self.tab_new_project.children():
            if isinstance(item, QLineEdit):
                temp.append(item.text())
                item.setText("")
        self.newproject_data = tuple(temp)
        self.tabWidget.setTabEnabled(3, True)
        self.tabWidget.setCurrentIndex(3)
        self.num_calcTab.setText(self.project_num)
        self.user_calcTab.setText(self.expert_name)

    def load_project_data(self):
        table = None
        if self.tabWidget.currentIndex() == 1:
            table = self.projects_table
        elif self.tabWidget.currentIndex() == 2:
            table = self.projects_table2
        if len(table.selectedItems()) == 0:
            QMessageBox.about(self, "Внимание!", "Не выбран проект для загрузки!")
        else:
            index = self.tabWidget.currentIndex()
            self.set_param_check(self.parameters, False)
            self.reset_params()
            data = [self.expert_name]
            row = table.currentRow()
            num = table.item(row, 1).text()
            data.append(num)
            date = table.item(row, 6).text()
            data.append(date)
            value = check_db.get_project(data)
            self.newproject_data = (value[3:])
            self.project_state = value[0]
            self.path = value[1]
            self.params = value[2].split(' ')
            self.project_num = num
            self.tabWidget.setTabEnabled(3, True)
            self.tabWidget.setCurrentIndex(3)
            self.btn_calculate.setEnabled(True)
            self.btn_reset_tasks.setEnabled(True)
            self.num_calcTab.setText(self.project_num)
            self.user_calcTab.setText(self.expert_name)
            self.set_param_check(self.params, True)
            try:
                self.create_rows()
            except FileNotFoundError:
                self.tabWidget.setTabEnabled(index, True)
                self.tabWidget.setCurrentIndex(index)
                if self.confirm_msg("Файлы проекта не найдены! Вы хотите удалить выбранный проект из списка?"):
                    self.delete_from_table(table)

    def remove_project(self):
        table = self.projects_table
        if len(self.projects_table.selectedItems()) == 0:
            QMessageBox.about(self, "Внимание!", "Не выбран проект для удаления!")
        else:
            if self.confirm_msg("Вы уверены, что хотите удалить выбранный проект?"):
                self.delete_from_table(table)

    def delete_from_table(self, table):
        data = [self.expert_name]
        row = table.currentRow()
        num = table.item(row, 1).text()
        data.append(num)
        date = table.item(row, 6).text()
        data.append(date)
        file_path = check_db.remove_project(data)
        index = file_path.rfind('/')
        line = file_path.replace('/', '\\')
        dir_path = f'\\{line[:index]}'
        dir = os.getcwd() + dir_path
        try:
            os.remove(file_path)
            os.rmdir(dir)
        except:
            pass
        self.show_user_projects(self.tabWidget.currentIndex())

    def create_dialog(self):
        if self.expert_name == '':
            QMessageBox.about(self, "Внимание!", "Не выбран пользователь!")
            self.switch_login.emit()
        else:
            self.check_enterdata()

    def check_enterdata(self):
        full_info = True
        for item in self.tab_new_project.children():
            if isinstance(item, QLineEdit) and item.text() == '':
                full_info = False
        if not full_info:
            QMessageBox.about(self, "Внимание!", "Не все поля заполнены!")
        else:
            project_num = self.enter_project_num.text()
            self.start_project(project_num)

    def set_param_check(self, params, bool):
        for el in self.group_params.children():
            for param in params:
                if param.lower() in el.objectName().title().lower():
                    el.setChecked(bool)

    def reset_params(self):
        self.path = 'data/Param_Tasks.xlsx'
        self.save_data = pd.DataFrame(
            columns=['Level', 'Pars_Name', 'Task', 'Task_Comments', 'Original_Task', 'State', 'Parameter'])
        self.param_tabs.clear()
        self.params = []
        self.rad = []

    def confirm_msg(self, text):
        messageBox = QMessageBox(self)
        messageBox.setWindowTitle("Подтверждение")
        messageBox.setIcon(QMessageBox.Question)
        messageBox.setText(text)
        buttonYes = messageBox.addButton("Да", QMessageBox.YesRole)
        buttonNo = messageBox.addButton("Нет", QMessageBox.NoRole)
        messageBox.setDefaultButton(buttonYes)
        messageBox.exec_()

        if messageBox.clickedButton() == buttonYes:
            return True
        elif messageBox.clickedButton() == buttonNo:
            return False

    def reset_tasks(self):
        if self.confirm_msg("Вы уверены, что хотите сбросить все отметки?"):
            tab_count = self.param_tabs.count()
            for i in range(tab_count):
                self.param_tabs.setCurrentIndex(i)
                tree = self.param_tabs.currentWidget()
                root = tree.invisibleRootItem()
                for level_num in range(root.childCount()):
                    level = root.child(level_num)
                    for j in range(level.childCount()):
                        child = level.child(j)
                        el = tree.itemWidget(child, 0)
                        if isinstance(el, QComboBox):
                            el.setCurrentText('Нет')
            self.param_tabs.setCurrentIndex(0)

    def set_params(self):
        if self.project_state in ['черновик', 'итог']:
            if self.confirm_msg('Вы уверены, что хотите изменить параметры (текущие отметки будут сброшены)?'):
                self.reset_params()
                self.get_params()
                if len(self.params) == 0:
                    QMessageBox.warning(self, 'Предупреждение', 'Не выбраны параметры оценки!')
                else:
                    self.create_rows()
                    self.btn_calculate.setEnabled(True)
                    self.btn_reset_tasks.setEnabled(True)
        else:
            self.reset_params()
            self.get_params()
            if len(self.params) == 0:
                QMessageBox.warning(self, 'Предупреждение', 'Не выбраны параметры оценки!')
            else:
                self.create_rows()
                self.btn_calculate.setEnabled(True)
                self.btn_reset_tasks.setEnabled(True)

    def get_params(self):
        if self.check_trl.isChecked():
            self.params.append('TRL')
        if self.check_mrl.isChecked():
            self.params.append('MRL')
        if self.check_erl.isChecked():
            self.params.append('ERL')
        if self.check_orl.isChecked():
            self.params.append('ORL')
        if self.check_crl.isChecked():
            self.params.append('CRL')

    def create_rows(self):

        for param in self.params:
            self.data = pd.read_excel(self.path, sheet_name=param)
            self.data['Parameter'] = param
            val = self.make_level_dict(self.data)

            self.tw = TreeWidget()
            self.param_tabs.addTab(self.tw, param)
            self.param_tabs.setCurrentIndex(self.params.index(param))
            self.param_tabs.setTabEnabled(self.params.index(param), True)

            for key, value in val.items():
                self.item_0 = QTreeWidgetItem(self.tw)
                self.item_0.setBackground(0, QColor("#D3D3D3"))
                self.item_0.setText(0, f'Уровень {key}')
                self.item_0.setBackground(1, QColor("#D3D3D3"))
                text = self.word_wrap(value[0], 90)
                self.item_0.setText(1, text)

                for v in value[1:]:
                    self.combo_task = QComboBox()
                    self.combo_task.setObjectName('combo_task')
                    self.combo_task.addItems(['Да', 'Нет', 'Не применимо'])
                    self.combo_task.adjustSize()
                    self.combo_task.setFixedSize(110, 20)
                    self.item_1 = QTreeWidgetItem(self.item_0, ["", ""])
                    if v[2] == 0:
                        self.combo_task.setCurrentText('Нет')
                    elif v[2] == 1:
                        self.combo_task.setCurrentText('Да')
                    else:
                        self.combo_task.setCurrentText('Не применимо')

                    self.tw.setItemWidget(self.item_1, 0, self.combo_task)
                    text = self.word_wrap(v[0], 90)
                    self.item_1.setText(1, text)
                    self.item_1.setBackground(0, QColor('#fcfcfc'))
                    self.item_1.setBackground(1, QColor('#fcfcfc'))
            self.save_data = self.save_data.append(self.data)
        self.param_tabs.setCurrentIndex(0)

    def word_wrap(self, line, x):
        start = 0
        if len(line) > x:
            while len(line) > (start + x):
                index = line.rfind(' ', start, start + x)
                line = (line[:index]).strip() + "\n" + (line[index:]).strip()
                start = index
        return line

    def make_level_dict(self, df):
        dict_levels = {}
        for row in range(df['Level'].shape[0]):
            if df['Level'][row] not in dict_levels:
                dict_levels[df['Level'][row]] = [df['Pars_Name'][row],
                                                 [df['Task'][row],
                                                  df['Task_Comments'][row],
                                                  df['State'][row]]]
            else:
                dict_levels[df['Level'][row]].append([df['Task'][row],
                                                      df['Task_Comments'][row],
                                                      df['State'][row]])
        return dict_levels

    def create_table_rows(self, text_levels):

        self.table_tprl_results.setRowCount(len(text_levels) - 1)
        self.table_tprl_results.setColumnCount(2)
        self.table_tprl_results.setColumnWidth(0, 50)
        self.table_tprl_results.setColumnWidth(1, 700)
        self.table_tprl_results.setStyleSheet('''font-size: 14px;''')

        for key, values in text_levels.items():
            if key == 'TPRL':
                self.label_main_tprl.setText(self.word_wrap(values, 95))

        text_levels.pop('TPRL')
        for i, key in enumerate(text_levels.items()):
            label1 = QLabel(key[0])
            label1.setContentsMargins(5, 5, 5, 5)
            label1.setStyleSheet("border-bottom: 1px solid grey;")
            label_text = self.word_wrap(key[1], 90)
            label2 = QLabel(label_text)
            label2.setContentsMargins(5, 5, 5, 5)
            label2.setStyleSheet("border-bottom: 1px solid grey;")
            self.table_tprl_results.setCellWidget(i, 0, label1)
            self.table_tprl_results.setCellWidget(i, 1, label2)
        self.table_tprl_results.setShowGrid(False)
        self.table_tprl_results.resizeRowsToContents()
        self.table_tprl_results.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.table_tprl_results.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.table_tprl_results.setEnabled(True)
        self.table_tprl_results.setFrameStyle(QFrame.NoFrame)

    def make_text_dict(self, op_data, diction):
        new_text_dict = {}
        for key, value in diction.items():
            for rank in range(op_data['Уровень'].shape[0]):
                if (key == 'TPRL') & (value == '0'):
                    new_text_dict['TPRL'] = 'Уровень зрелости инновационного проекта/технологии  = 0'
                elif (key == 'TPRL') & (value == '--'):
                    new_text_dict['TPRL'] = 'Уровень зрелости инновационного проекта/технологии не рассчитан, т.к. ' \
                                            'не были выбраны все параметры'
                elif op_data['Уровень'][rank] == int(float(value)):
                    new_text_dict[key] = op_data[key][rank]
        return new_text_dict

    def make_text(self):
        op_data = pd.read_excel('data/Levels.xlsx')
        text_dict = {'TPRL': str(self.tprl_min)}
        text_dict.update(self.d3)
        text_levels = self.make_text_dict(op_data, text_dict)
        self.create_table_rows(text_levels)

    def calculate(self):
        self.risk_flag = True
        self.text_warning = ''
        self.save_data.drop(['State'], axis='columns', inplace=True)
        self.label_project_num.setText(self.project_num)
        self.label_expert_name.setText(self.expert_name)
        self.risks_label_project_num.setText(self.project_num)
        self.risks_label_expert_name.setText(self.expert_name)
        self.tabWidget.setTabEnabled(4, True)
        self.tabWidget.setTabEnabled(5, True)
        self.tabWidget.setCurrentIndex(4)
        self.check_draft.setEnabled(True)
        self.check_draft.setChecked(False)
        self.btn_save_results.setEnabled(True)
        self.d1 = {}
        d2 = {}
        self.d3 = {}
        new_state = []
        l2 = []
        for param in self.params:
            self.param_tabs.setCurrentIndex(self.params.index(param))
            tree = self.param_tabs.currentWidget()
            root = tree.invisibleRootItem()
            levels = root.childCount()
            for level_num in range(levels):
                level = root.child(level_num)
                l1 = []
                for kid in range(level.childCount()):
                    child = level.child(kid)
                    el = tree.itemWidget(child, 0)
                    if isinstance(el, QComboBox):
                        combo_text = el.currentText()
                        if combo_text == 'Да':
                            l1.append(1)
                            new_state.append(1)
                        elif combo_text == 'Нет':
                            l1.append(0)
                            new_state.append(0)
                        else:
                            l1.append(-1)
                            new_state.append(-1)
                if param not in self.d1:
                    l2 = []
                    l2.append(l1)
                    self.d1[param] = l2
                else:
                    self.d1[param].append(l1)
            for key, values in self.d1.items():
                first_list = []
                for value in values:
                    new_list = []
                    for v in range(len(value)):
                        if value[v] == 1:
                            new_list.append(1)
                        if value[v] == 0:
                            new_list.append(0)
                    first_list.append(new_list)
                d2[key] = first_list
        self.save_data['State'] = new_state
        for new_key, new_values in d2.items():
            l_n = []
            for new_value in new_values:
                try:
                    new_value = sum(new_value) / len(new_value)
                    n = Decimal(f'{new_value}')
                    new_value = n.quantize(Decimal('1.0'), rounding='ROUND_HALF_UP')
                except Exception:
                    new_value = 0.0
                l_n.append(new_value)
            d2[new_key] = l_n
        for d2_keys, d2_values in d2.items():
            summary = 0
            for d2_value in range(len(d2_values)):
                if d2_values[d2_value] == 1:
                    if d2_value > 0:
                        if d2_values[d2_value - 1] != 1:
                            self.text_warning = 'Вы не отметили задачи предыдущих уровней.\n' \
                                                'Риски рассчитаны неправильно!!!'
                            self.risk_flag = False
                    summary = d2_value + 1
                elif 0 < d2_values[d2_value] < 1:
                    if summary == d2_value:
                        summary += d2_values[d2_value]
            self.d3[d2_keys] = str(summary)

        # if len(self.params) == 5:  # Оценка рисков
        #     self.risks_table.setVisible(True)
        #     self.count_risks(self.save_data)
        # else:
        #     self.text_warning = 'Комплексная оценка рисков не проводилась, т.к. не все параметры выбраны!'
        #     self.risks_table.setVisible(False)
        #     self.risk_flag = False
        # self.risks_warning_label.setText(self.text_warning)
        # self.btn_report_risks.setEnabled(self.risk_flag)

        self.show_risks()

        for par in Window.parameters:
            if par not in self.d3.keys():
                self.d3[par] = '0'
        for iter_k, iter_v in self.d3.items():
            # iter_v = round(float(iter_v), 1)

            self.d3[iter_k] = str(iter_v)
        self.param_tabs.setCurrentIndex(0)
        self.frame_results.setEnabled(True)
        self.show_results(self.d3)
        if len(self.params) == 5:
            self.chart = Chart(self.d3, self.lay)
        self.make_text()

    def save_results(self):
        # ---------------Формируем dataframe с результатами------------------------
        now = datetime.datetime.now()
        date = now.strftime("%d.%m.%Y %H:%M")
        file_date = now.strftime("%d.%m.%Y %H-%M")
        if self.check_draft.isChecked():
            self.project_state = 'черновик'
        else:
            self.project_state = 'итог'
        chars = ':\/*?<>"|'
        saved_file_name = self.project_num
        for ch in chars:
            if ch in saved_file_name:
                saved_file_name = saved_file_name.replace(ch, '_')
        if '\\' in saved_file_name:
            saved_file_name = saved_file_name.replace('\\', '_')
        project_dir = f'{saved_file_name}_{file_date}'
        new_file_name = f'{saved_file_name}_{file_date}.xlsx'
        total = [[self.expert_name, self.project_num, date, self.label_tprl_min_result.text(),
                  self.label_tprl_average_result.text(), self.label_trl_result.text(),
                  self.label_mrl_result.text(), self.label_erl_result.text(),
                  self.label_orl_result.text(), self.label_crl_result.text(), self.project_state]]
        features = np.array(total)
        columns = ['Expert', 'Project Number', 'Date', 'TPRLmin', 'TPRLaverage', 'TRL', 'MRL', 'ERL', 'ORL', 'CRL',
                   'Статус']
        frame = pd.DataFrame(data=features, columns=columns)
        # ---------------Записываем данные в файл----------------------------------
        file_name = 'Results.xlsx'
        if os.path.isfile(file_name):
            old_frame = pd.read_excel('Results.xlsx')
            old_frame = old_frame.append(frame, ignore_index=True)
            old_frame.to_excel('Results.xlsx', index=False)
        else:
            file = open('Results.xlsx', 'w')
            frame.to_excel('Results.xlsx', index=False)
            file.close()
        # ---------------Записываем данные в файл_2--------------------------------------------
        if not os.path.isdir("Projects"):
            os.mkdir("Projects")
        if not os.path.isdir(f"Projects/{self.expert_name}"):
            os.mkdir(f"Projects/{self.expert_name}")
        if self.project_state == 'черновик':
            if not os.path.isdir(f"Projects/{self.expert_name}/Черновики"):
                os.mkdir(f"Projects/{self.expert_name}/Черновики")
            if not os.path.isdir(f"Projects/{self.expert_name}/Черновики/{saved_file_name}"):
                os.mkdir(f"Projects/{self.expert_name}/Черновики/{saved_file_name}")
            self.path = f"Projects/{self.expert_name}/Черновики/{saved_file_name}/{new_file_name}"
            writer = pd.ExcelWriter(self.path)
            for param in self.params:
                new_save_data = self.save_data.loc[self.save_data['Parameter'].isin([param])]
                new_save_data.drop(['Parameter'], axis='columns', inplace=True)
                new_save_data.to_excel(writer, sheet_name=param, index=False)
                writer.save()
            writer.close()
        else:
            if not os.path.isdir(f"Projects/{self.expert_name}/Завершенные"):
                os.mkdir(f"Projects/{self.expert_name}/Завершенные")
            if not os.path.isdir(f"Projects/{self.expert_name}/Завершенные/{saved_file_name}"):
                os.mkdir(f"Projects/{self.expert_name}/Завершенные/{saved_file_name}")
            self.path = f"Projects/{self.expert_name}/Завершенные/{saved_file_name}/{new_file_name}"
            full_dir = f"Projects/{self.expert_name}/Завершенные/{saved_file_name}"
            writer = pd.ExcelWriter(self.path)
            for param in self.params:
                new_save_data = self.save_data.loc[self.save_data['Parameter'].isin([param])]
                new_save_data.drop(['Parameter'], axis='columns', inplace=True)
                new_save_data.to_excel(writer, sheet_name=param, index=False)
                writer.save()
            writer.close()
            self.chart.save_chart(full_dir, project_dir)

        # сохранение проекта в БД
        params = ' '.join(self.params)
        self.saveproject_data = (date, self.project_state, self.path, params)
        data = self.newproject_data + self.saveproject_data
        check_db.save_project(self.expert_name, data)

        QMessageBox.about(self, 'Сохранение результатов', 'Результаты успешно сохранены')
        self.btn_save_results.setEnabled(False)
        self.check_draft.setEnabled(False)

    def report_ugt(self):
        res_list = [float(self.label_trl_result.text()),
                    float(self.label_mrl_result.text()),
                    float(self.label_erl_result.text()),
                    float(self.label_orl_result.text()),
                    float(self.label_crl_result.text())]
        results = []
        for i in range(len(self.parameters)):
            for param in self.params:
                if self.parameters[i] == param:
                    results.append(res_list[i])
        date = datetime.datetime.now().strftime("%d.%m.%Y %H:%M")
        data = {}
        for param in self.params:
            new_save_data = self.save_data.loc[self.save_data['Parameter'].isin([param])]
            new_save_data.drop(['Parameter'], axis='columns', inplace=True)
            data[param] = new_save_data
        self.pdf_data = (
            [date, self.project_num, self.expert_name, self.params, results,
             [self.tprl_min, self.label_main_tprl.text()]],
            data
        )
        new_report_ugt = ReportUgt(self.pdf_data, self.d1)
        new_report_ugt.set_data()

    def show_results(self, res):
        res_list = []
        for k_res, v_res in res.items():
            n = Decimal(f'{v_res}')
            v = n.quantize(Decimal('1.0'), rounding='ROUND_HALF_UP')
            if k_res == 'TRL':
                self.label_trl_result.setText(f'{v}')
            elif k_res == 'MRL':
                self.label_mrl_result.setText(f'{v}')
            elif k_res == 'ERL':
                self.label_erl_result.setText(f'{v}')
            elif k_res == 'ORL':
                self.label_orl_result.setText(f'{v}')
            elif k_res == 'CRL':
                self.label_crl_result.setText(f'{v}')
        show_res = res.copy()
        if len(self.params) < 5:
            self.tprl_average = '--'
            self.tprl_min = '--'
            self.label_tprl_average_result.setText(self.tprl_average)
            self.label_tprl_min_result.setText(self.tprl_min)
        else:
            while float(max(show_res.values())) - float(min(show_res.values())) >= 2:
                x = float(max(show_res.values()))
                for d3_k, d3_v in show_res.items():
                    if float(d3_v) == x:
                        d3_v = round(float(d3_v) - 1, 1)
                    show_res[d3_k] = str(d3_v)
            for new_v in show_res.values():
                res_list.append(float(new_v))
            self.tprl_average = float(sum(res_list) / len(res_list))
            number = Decimal(f'{self.tprl_average}')
            self.tprl_average = number.quantize(Decimal("1.0"), rounding='ROUND_HALF_UP')
            self.tprl_min = int(self.tprl_average)
            self.label_tprl_average_result.setText(str(self.tprl_average))
            self.label_tprl_min_result.setText(str(self.tprl_min))

    def show_risks(self):
        self.risk_param_tabs.clear()
        for param in self.params:
            self.risk_param_tab = QWidget()
            self.risk_param_tabs.addTab(self.risk_param_tab, param)
            self.risk_param_tabs.setCurrentIndex(self.params.index(param))
            self.risk_param_tabs.setTabEnabled(self.params.index(param), True)
            self.frame_param_risks = QFrame(self.risk_param_tab)
            self.frame_param_risks.move(0, 0)
            self.frame_param_risks.setFixedSize(820, 450)
            self.frame_param_risks.setFrameShape(QFrame.StyledPanel)
            self.frame_param_risks.setFrameShadow(QFrame.Raised)
            param_risks_values = self.get_task_results(param)[param]
            self.create_param_risks_table(self.frame_param_risks, param_risks_values)
        self.risk_param_tabs.setCurrentIndex(0)
        self.create_result_risks_table()

    def get_task_results(self, param):
        lvl = int(float(self.d3[param]))
        new_result = {}
        self.param_tabs.setCurrentIndex(self.params.index(param))
        tree = self.param_tabs.currentWidget()
        root = tree.invisibleRootItem()
        if lvl == 9:
            level = root.child(lvl - 1)
        else:
            level = root.child(lvl)
        lvl_result = f"{level.text(0)}. {level.text(1)}"
        l1 = []
        for kid in range(level.childCount()):
            child = level.child(kid)
            text = child.text(1).split("\n")
            text = " ".join(text)
            el = tree.itemWidget(child, 0)
            combo_text = el.currentText()
            l1.append([text, combo_text])
        l2 = [lvl_result, l1]
        new_result[param] = l2
        return new_result

    def create_param_risks_table(self, frame, param_risks_values):
        lvl_txt = param_risks_values[0]
        font = QFont()
        font.setPointSize(10)
        font.setBold(True)
        self.lvl_text_label = QLabel(frame)
        self.lvl_text_label.setGeometry(QRect(5, 5, 800, 30))
        self.lvl_text_label.setFont(font)
        self.lvl_text_label.setWordWrap(True)
        self.lvl_text_label.setAlignment(Qt.AlignCenter)
        self.lvl_text_label.setObjectName("lvl_text_label")
        self.lvl_text_label.setText(lvl_txt)

        self.param_risks_table = QTableWidget(frame)
        self.param_risks_table.move(5, 40)
        self.param_risks_table.setMinimumWidth(805)
        self.param_risks_table.setFixedHeight(250)
        self.param_risks_table.setContentsMargins(0, 0, 0, 0)
        self.param_risks_table.horizontalHeader().setVisible(True)
        self.param_risks_table.verticalHeader().setVisible(False)
        self.param_risks_table.setSelectionMode(QAbstractItemView.NoSelection)
        self.param_risks_table.setFocusPolicy(Qt.NoFocus)
        self.param_risks_table.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.param_risks_table.setColumnCount(3)
        columns = [["Задача", 590],
                   ["Прогноз\nсвоевременного\nисполнения задачи", 110],
                   ["Вероятность\nреализации\nриска, %", 80]]
        for i in range(3):
            item = QTableWidgetItem()
            item.setTextAlignment(Qt.AlignCenter)
            self.param_risks_table.setColumnWidth(i, columns[i][1])
            self.param_risks_table.setHorizontalHeaderItem(i, item)
            item.setText(columns[i][0])
        self.param_risks_table.setStyleSheet("QHeaderView::section {background-color: #82898E; color: #ffffff;}")
        data = param_risks_values[1]
        rows_count = len(data)
        self.param_risks_table.setRowCount(rows_count)
        n = 0
        total = rows_count
        for row in range(rows_count):
            self.param_risks_table.setRowHeight(row, 60)
            task_text = self.word_wrap(data[row][0], 580)
            item = QTableWidgetItem()
            item.setTextAlignment(Qt.AlignLeft)
            item.setText(task_text)
            self.param_risks_table.setItem(row, 0, item)
            if data[row][1] == "Да":
                item = QTableWidgetItem()
                item.setTextAlignment(Qt.AlignCenter)
                item.setText("1")
                self.param_risks_table.setItem(row, 1, item)
                n += 1
            elif data[row][1] == "Не применимо":
                text = QTableWidgetItem()
                text.setTextAlignment(Qt.AlignCenter)
                text.setText(data[row][1])
                self.param_risks_table.setItem(row, 1, text)
                total -= 1
            elif data[row][1] == "Нет":
                self.risk_spin = QDoubleSpinBox()
                self.risk_spin.setMinimum(0)
                self.risk_spin.setMaximum(0.99)
                self.risk_spin.setSingleStep(0.01)
                self.param_risks_table.setCellWidget(row, 1, self.risk_spin)
                self.risk_spin.valueChanged.connect(self.risk_realization)
        font.setPointSize(12)
        self.param_risk_label = QLabel(frame)
        self.param_risk_label.setGeometry(QRect(5, 350, 800, 30))
        self.param_risk_label.setFont(font)
        self.param_risk_label.setWordWrap(True)
        self.param_risk_label.setAlignment(Qt.AlignLeft)
        self.param_risk_label.setObjectName("param_risk_label")
        self.param_risk_label.setStyleSheet("color: red;")
        self.param_risk_label.setText("")
        self.param_risks_table.setSpan(0, 2, rows_count, 1)
        self.risk_realization()
        param_i = 1 - (n / total)
        param_r = float(self.param_risks_table.item(0, 2).text().rstrip("%")) / 100
        param_ir = round((param_i * param_r), 2)
        lvl = lvl_txt[8]
        param_name = self.risk_param_tabs.tabText(self.risk_param_tabs.currentIndex())
        self.param_risk_label.setText(f"Итоговая оценка риска уровня готовности {lvl} "
                                      f"по параметру {param_name}: {param_ir}")

    @pyqtSlot()
    def risk_realization(self):
        table = None
        tab = self.risk_param_tabs.currentWidget()
        frame = tab.children()[0]
        widgets = frame.children()
        for el in widgets:
            if isinstance(el, QTableWidget):
                table = el
                break
        count = 1
        rows = table.rowCount()
        n = 0                   # число выполненных задач
        total = rows            # общее число задач за вычетом "не применимо"
        for row in range(rows):
            try:
                num = float(table.item(row, 1).text())
                count *= num
                n += 1
            except AttributeError:
                num = float(table.cellWidget(row, 1).value())
                count *= num
            except ValueError:
                total -= 1
        risk = 1 - count
        result = round((risk * 100), 1)
        item = QTableWidgetItem()
        item.setTextAlignment(Qt.AlignCenter)
        item.setText(f"{result}%")
        table.setItem(0, 2, item)

        param_i = 1 - (n / total)
        param_r = risk
        param_ir = round((param_i * param_r), 2)
        lvl = widgets[0].text()[8]
        param_name = self.risk_param_tabs.tabText(self.risk_param_tabs.currentIndex())
        result_risk_param_text = f"Итоговая оценка риска уровня готовности {lvl} по параметру {param_name}: {param_ir}"
        widgets[2].setText(result_risk_param_text)

    def create_result_risks_table(self):
        pass

    def set_task_lvl_label(self, text):
        font = QFont()
        font.setPointSize(12)
        font.setBold(False)
        font.setUnderline(True)
        self.task_lvl_text = QLabel()
        self.task_lvl_text.move(0, 80)
        self.task_lvl_text.setFont(font)
        self.task_lvl_text.setWordWrap(True)
        self.task_lvl_text.setMaximumWidth(800)
        self.task_lvl_text.setMaximumHeight(40)
        self.task_lvl_text.setText(text)
        self.task_lvl_text.setAlignment(Qt.AlignVCenter)
        self.task_lvl_text.setObjectName("task_lvl_text")

    def show_help(self):
        self.help_dialog = HelpDialog(self)
        self.help_dialog.show()

    def closeEvent(self, event):
        if self.confirm_msg("Вы уверены, что хотите закрыть программу?"):
            event.accept()
        else:
            event.ignore()
Example #13
0
class Export(QFrame):
    export_text = "Export"
    exporting_text = "Exporting..."

    def __init__(self, app):
        super().__init__()
        # initialize our variables
        self.app = app
        self.export_button = None
        self.progress_bar = None
        self.projects = get_projects()
        self.project_dropdown = None
        self.init_ui()

    def init_ui(self):
        # make our UI
        self.setObjectName("content")
        layout = QHBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)

        # our main content area
        content = QFrame()
        content_layout = QVBoxLayout()

        # some info
        title = QLabel("Export")
        title.setObjectName("h1")
        description = QLabel(
            "Export your labeled dataset from a Lobe project.")
        description.setObjectName("h2")

        # project dropdown
        project_label = QLabel("Project:")
        project_label.setObjectName("separate")
        self.project_dropdown = QComboBox()
        self.project_dropdown.setSizeAdjustPolicy(QComboBox.AdjustToContents)
        self.project_dropdown.setSizePolicy(QSizePolicy.Preferred,
                                            QSizePolicy.Expanding)
        project_container = NoStretch(self.project_dropdown)
        self.populate_projects()

        # button
        self.export_button = QPushButton(self.export_text)
        self.export_button.setEnabled(True)
        self.export_button.clicked.connect(self.export)
        export_container = NoStretch(self.export_button)
        export_container.setObjectName("separate")

        self.progress_bar = QProgressBar()
        self.progress_bar.hide()

        # make our content layout
        content_layout.addWidget(title)
        content_layout.addWidget(description)
        content_layout.addWidget(project_label)
        content_layout.addWidget(project_container)
        content_layout.addWidget(export_container)
        content_layout.addWidget(self.progress_bar)
        content_layout.addStretch(1)
        content.setLayout(content_layout)

        layout.addWidget(content)
        layout.addStretch(1)
        self.setLayout(layout)

    def populate_projects(self):
        self.projects = get_projects()
        self.project_dropdown.clear()
        self.project_dropdown.addItems([name for name, _ in self.projects])
        self.project_dropdown.adjustSize()

    def export(self):
        # disable the buttons so we can't click again
        self.export_button.setEnabled(False)
        self.export_button.setText(self.exporting_text)
        self.progress_bar.setValue(0)
        self.progress_bar.show()
        self.app.processEvents()
        destination_directory = QFileDialog.getExistingDirectory(
            self, "Select Output Directory")
        # if they hit cancel, don't download
        if not destination_directory:
            self.done()
            return
        # otherwise try exporting to the desired location
        try:
            project_name, project_id = self.projects[
                self.project_dropdown.currentIndex()]
            export_dir = os.path.join(destination_directory, project_name)
            # rename the directory if there is a conflict
            rename_idx = 1
            while os.path.exists(export_dir):
                export_dir = os.path.abspath(
                    os.path.join(destination_directory,
                                 f"{project_name} ({rename_idx})"))
                rename_idx += 1
            export_dataset(project_id=project_id,
                           destination_dir=export_dir,
                           progress_hook=self.progress_hook)
        except Exception as e:
            QMessageBox.about(self, "Alert", f"Error exporting dataset: {e}")
            self.done()

    def progress_hook(self, current, total):
        self.progress_bar.setValue(float(current) / total * 100)
        if current == total:
            self.done()
        # make sure to update the UI
        self.app.processEvents()

    def done(self):
        self.progress_bar.setValue(0)
        self.progress_bar.hide()
        self.export_button.setEnabled(True)
        self.export_button.setText(self.export_text)
        self.app.processEvents()
Example #14
0
    def initUI(self):
        self.setGeometry(300, 300, 600, 600)
        self.setWindowTitle('Drawing home')
        self.width = 175  #default settings
        self.height = 100
        self.roofHeight = 50
        self.mainColor1 = QColor(255, 255, 127)
        self.mainColor2 = QColor(255, 85, 0)
        self.roofColor = QColor(199, 250, 252)
        self.doorColor = QColor(255, 255, 255)
        self.lightColor = QColor(255, 219, 41)
        self.windowStyle = "Round window"
        self.roomNumber = 1

        drawButton = QPushButton(
            "Move cursor here to update the object, if it was not happened",
            self)
        drawButton.setFont(QFont("Comic Sans MS", 11, QFont.Normal))
        drawButton.move(40, 60)
        drawButton.adjustSize()
        #sliders etc.
        self.changeWidth = QSlider(Qt.Horizontal, self)
        self.changeWidth.setFocusPolicy(Qt.NoFocus)
        self.changeWidth.setStyleSheet(sldStyle)  #use our own style!
        self.changeWidth.setGeometry(30, 150, 100, 30)
        self.changeWidth.valueChanged[int].connect(self.changeWidthF)
        self.changeHeight = QSlider(Qt.Horizontal, self)
        self.changeHeight.setFocusPolicy(Qt.NoFocus)
        self.changeHeight.setStyleSheet(sldStyle)
        self.changeHeight.setGeometry(30, 220, 100, 30)
        self.changeHeight.valueChanged[int].connect(self.changeHeightF)
        self.changeRoofHeight = QSlider(Qt.Horizontal, self)
        self.changeRoofHeight.setFocusPolicy(Qt.NoFocus)
        self.changeRoofHeight.setStyleSheet(sldStyle)
        self.changeRoofHeight.setGeometry(30, 290, 100, 30)
        self.changeRoofHeight.valueChanged[int].connect(self.changeRoofHeightF)
        changeWindowStyle = QComboBox(self)
        changeWindowStyle.addItem("Round window")
        changeWindowStyle.addItem("2-part window")
        changeWindowStyle.addItem("No window")
        changeWindowStyle.move(30, 365)
        changeWindowStyle.setFont(QFont("Tahoma", 10, QFont.Normal))
        changeWindowStyle.activated[str].connect(self.changeWindowStyle)
        changeWindowStyle.adjustSize()
        changeIllumination = QCheckBox('Neon Light', self)
        changeIllumination.move(30, 410)
        changeIllumination.setFont(QFont("Segoe Print", 10, QFont.Normal))
        changeIllumination.adjustSize()
        changeIllumination.stateChanged.connect(self.changeIllumination)
        changeRoomNumber = QComboBox(self)
        changeRoomNumber.addItem("1")
        changeRoomNumber.addItem("2")
        changeRoomNumber.move(30, 505)
        changeRoomNumber.setFont(QFont("Tahoma", 10, QFont.Normal))
        changeRoomNumber.activated[int].connect(self.changeRoomNumber)
        #labels
        changeW = QLabel("Width", self)
        changeW.move(30, 120)
        changeW.setFont(QFont("Segoe Print", 10, QFont.Normal))
        changeH = QLabel("Height", self)
        changeH.move(30, 190)
        changeH.setFont(QFont("Segoe Print", 10, QFont.Normal))
        changeRH = QLabel("Roof level", self)
        changeRH.move(30, 260)
        changeRH.setFont(QFont("Segoe Print", 10, QFont.Normal))
        changeWS = QLabel("Window style", self)
        changeWS.move(30, 330)
        changeWS.setFont(QFont("Segoe Print", 10, QFont.Normal))
        changeWS.adjustSize()
        changeRN = QLabel("Number of rooms", self)
        changeRN.move(30, 450)
        changeRN.setFont(QFont("Segoe Print", 10, QFont.Normal))
        changeRN.adjustSize()
        changeRN1 = QLabel("on the 2nd floor", self)
        changeRN1.move(30, 470)
        changeRN1.setFont(QFont("Segoe Print", 10, QFont.Normal))
        changeRN1.adjustSize()
        #toolbar actions
        roofColorAction = QAction(QIcon('colorR.png'),
                                  'Change color of the roof', self)
        roofColorAction.triggered.connect(self.changeRoofColor)
        color1Action = QAction(QIcon('color2.png'),
                               'Change color of the upper part', self)
        color1Action.triggered.connect(self.changeColor1)
        color2Action = QAction(QIcon('color1.png'),
                               'Change color of the lower part', self)
        color2Action.triggered.connect(self.changeColor2)
        doorColorAction = QAction(QIcon('colorD.png'),
                                  'Change color of the door', self)
        doorColorAction.triggered.connect(self.changeDoorColor)
        randomizeAction = QAction(QIcon('random.png'), 'Randonize your house',
                                  self)
        randomizeAction.triggered.connect(self.randomize)
        toolbar = self.addToolBar('Menu')
        toolbar.setIconSize(QSize(45, 45))
        toolbar.addAction(roofColorAction)
        toolbar.addAction(color2Action)
        toolbar.addAction(color1Action)
        toolbar.addAction(doorColorAction)
        toolbar.addAction(randomizeAction)

        self.show()
Example #15
0
class LookupView(QDialog):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):

        self.nusubut = QPushButton('确定', self)
        self.nusubut.clicked.connect(self.Sure)
        self.nusubut.resize(self.nusubut.sizeHint())

        self.exportbut = QPushButton('导出', self)
        self.exportbut.clicked.connect(self.Export)
        self.exportbut.resize(self.exportbut.sizeHint())
        self.exportbut.setEnabled(False)

        self.setGeometry(400, 400, 300, 150)
        label1 = QLabel("请输入密码:")
        label2 = QLabel("请选择专业:")
        self.label3 = QLabel(self)  #Label3
        self.passwd = QLineEdit(self)

        self.combo = QComboBox(self)
        self.combo.addItem("请选择")

        self.setWindowTitle("查看")

        lookupLayout = QGridLayout()
        lookupLayout.addWidget(self.label3, 0, 1)
        lookupLayout.addWidget(label1, 1, 0)
        lookupLayout.addWidget(label2, 2, 0)
        lookupLayout.addWidget(self.nusubut, 1, 2)
        lookupLayout.addWidget(self.passwd, 1, 1)
        lookupLayout.addWidget(self.combo, 2, 1)
        #lookupLayout.addWidget(nusubut,0,2)
        lookupLayout.addWidget(self.exportbut, 3, 2)
        self.setLayout(lookupLayout)

    def Export(self):

        conn = mysql.connector.connect(user='******',
                                       password='******',
                                       database='selectwork')
        result = conn.cursor()
        result.execute('select zy from zw_zy where zw = %s',
                       (self.stuProfession, ))
        zyPro = result.fetchall()[0][0]
        result.execute('select sno,sname,splace from ' + zyPro + '_student ')
        exportResult = result.fetchall()
        print(str(exportResult[0][0]))
        if os.path.exists(self.stuProfession + '.txt'):
            os.remove(self.stuProfession + '.txt')
        with open(self.stuProfession + '.txt', 'w', encoding='utf-8') as f:
            for i in range(len(exportResult)):
                if exportResult[i][2] == None:
                    f.write(
                        str(exportResult[i][0]) + ' ' +
                        bytes.decode(exportResult[i][1]) + ' None\n')
                else:
                    f.write(
                        str(exportResult[i][0]) + ' ' +
                        bytes.decode(exportResult[i][1]) + ' ' +
                        bytes.decode(exportResult[i][2]) + '\n')
        #print(exportResult)

    def GetProfession(self):
        conn = mysql.connector.connect(user='******',
                                       password='******',
                                       database='selectwork')
        result = conn.cursor()
        result.execute('select zw from zw_zy')
        valuesPro = result.fetchall()
        profession = []
        #print(valuesPro[1][0])
        for i in range(len(valuesPro)):
            profession.append(valuesPro[i][0])
        result.close()
        conn.close()
        return profession

    def onActivated(self, index):
        self.exportbut.setEnabled(False)
        self.stuProfession = self.combo.itemText(index)
        if self.stuProfession != '请选择':
            self.exportbut.setEnabled(True)

    def checkPasswd(self):
        inputPasswd = self.passwd.text()
        #print(inputPasswd)
        hash_md5 = hashlib.md5(str.encode(inputPasswd))
        inputPasswd = hash_md5.hexdigest()
        if inputPasswd == 'dbc627bdd5006763ac320b4c4813f694':
            return True
        else:
            return False

    def Sure(self):
        if self.checkPasswd():
            self.label3.setText('密码正确,请选择专业')
            self.label3.adjustSize()
            #print(self.stuProfession)
            select = self.GetProfession()
            for i in range(len(select)):
                self.combo.addItem(select[i])
                self.combo.adjustSize()
            self.combo.activated.connect(self.onActivated)
        else:
            self.combo.clear()
            self.combo.addItem('密码错误')
            self.label3.setText('请重新输入密码')
            self.label3.adjustSize()
            self.exportbut.setEnabled(False)
Example #16
0
class MainWindow(QMainWindow):
    """
    Main window class
    """
    def __init__(self, project_model: ProjectModel):
        """
        Main window class constructor

        :param project_model: ProjectModel
        """
        super().__init__()

        self.__title = 'MyTableCreator'
        self.__top = 150
        self.__left = 350
        self.__height = 500
        self.__width = 800
        self.__buttons = MyButton(self)
        self.__labels = MyLabel(self)
        self.__project_model = project_model
        self.__project_controller = ProjectController()
        self.init_window()

    def init_window(self):
        """
        Init Window function
        this function sets all window widgets
        """
        self.setWindowTitle(self.__title)
        self.setGeometry(self.__left, self.__top, self.__width, self.__height)
        self.setFixedSize(self.__width, self.__height)

        self.button_1 = self.__buttons.create_button(
            'Wyszukaj', 550, 75, 200, 30, 'Kliknij aby przeszukać tabele',
            self.browse)
        self.button_1.setEnabled(False)

        self.button_2 = self.__buttons.create_button(
            'Edytuj wiersz', 550, 125, 200, 30, 'Kliknij aby edytować wiersz',
            self.edit_row)
        self.button_2.setEnabled(False)

        self.button_3 = self.__buttons.create_button(
            'Dodaj wiersz', 550, 175, 200, 30, 'Kliknij aby dodać wiersz',
            self.add_row)

        self.button_3.setEnabled(False)

        self.button_4 = self.__buttons.create_button(
            'Usuń wiersz', 550, 225, 200, 30, 'Kliknij aby usunąć wiersz',
            self.remove_row)

        self.button_4.setEnabled(False)

        self.button_5 = self.__buttons.create_button(
            'Edytuj tabelę', 550, 275, 200, 30, 'Kliknij aby edytować tabelę',
            self.edit_table)

        self.button_5.setEnabled(False)

        self.button_6 = self.__buttons.create_button(
            'Dodaj tabelę', 550, 325, 200, 30, 'Kliknij aby dodać nową tabelę',
            self.create_table)
        self.button_7 = self.__buttons.create_button(
            'Usuń tabelę', 550, 375, 200, 30, 'Kliknij aby usunąć tabelę',
            self.remove_table)

        self.button_7.setEnabled(False)

        self.button_8 = self.__buttons.create_button(
            'Otwórz plik', 300, 425, 200, 30, 'Kliknij aby otworzyć plik',
            self.load_structure)
        self.button_9 = self.__buttons.create_button(
            'Zakończ', 550, 425, 200, 30, 'Kliknij aby wyjść z programu',
            self.end)

        self.__combo_box_1 = QComboBox(self)
        self.__combo_box_1.move(400, 125)
        self.__combo_box_1.addItem('Wybierz tabele')
        self.__combo_box_1.adjustSize()
        self.__combo_box_1.currentTextChanged.connect(self.set_combo_box_2)

        self.__combo_box_2 = QComboBox(self)
        self.__combo_box_2.move(400, 175)
        self.__combo_box_2.addItem('Wybierz rekord')
        self.__combo_box_2.adjustSize()
        self.__combo_box_2.currentTextChanged.connect(self.combo_box_2_changed)

        self.show()

    def end(self):
        """
        End method
        this method initializes new writeFile object (window)
        after executing write to file procedure, window is closed
        :return:
        """
        self.writeFile = WriteFile(self.__project_model)
        self.writeFile.setModal(True)
        self.writeFile.exec()
        self.close()

    def browse(self):
        """
        browse method
        this method checks if table was chosen from combo box 1 and initializes new BrowseWindow object
        :return:
        """
        try:
            current_table = self.__combo_box_1.currentText()
            self.__project_controller.check_removed_table_name(current_table)
            browse_window = BrowseWindow(self.__project_model, current_table)
            browse_window.setModal(True)
            browse_window.exec()
            self.set_combo_box_2()
        except Exception as exception:
            warning = WarningWindow(str(exception))
            warning.setModal(True)
            warning.exec()

    def edit_row(self):
        """
        edit row method
        this method checks if table and raw were chosen from combo boxes and initializes new EditRowsWindow object
        :return:
        """
        try:
            current_table = self.__combo_box_1.currentText()
            current_row = self.__combo_box_2.currentText()
            self.__project_controller.check_removed_table_name(current_table)
            self.__project_controller.check_removed_row(current_row)

            new_table = Table(
                current_table,
                self.__project_model.get_table(
                    current_table).get_number_of_columns(), 1,
                self.__project_model.get_table(
                    current_table).get_column_dict(), [
                        self.__project_model.get_table_row(
                            current_table,
                            self.__project_model.get_row_index(
                                current_table, current_row))
                    ])

            edit_row_window = EditRowsWindow(self.__project_model, new_table)
            edit_row_window.setModal(True)
            edit_row_window.exec()
            self.set_combo_box_2()

        except Exception as exception:

            warning = WarningWindow(str(exception))
            warning.setModal(True)
            warning.exec()

    def remove_row(self):
        """
        removeRow method
        this method checks if table and row were chosen from combo boxes and initializes new ConfirmRemoveWindow object
        """
        try:
            table_name = self.__combo_box_1.currentText()
            row = self.__combo_box_2.currentText()
            self.__project_controller.check_removed_table_name(table_name)
            self.__project_controller.check_removed_row(row)

            confirm_remove_row = ConfirmRemoveRowWindow(
                self.__project_model, self.__combo_box_2, table_name)
            confirm_remove_row.setModal(True)
            confirm_remove_row.exec()

        except Exception as exception:
            warning = WarningWindow(str(exception))
            warning.setModal(True)
            warning.exec()

    def load_structure(self):
        """
        Load structure method
        this method initializes new LoadFile object (window)
        """
        load_file = LoadFile(self.__project_model, self.__combo_box_1)
        load_file.setModal(True)
        load_file.exec()

    def edit_table(self):
        """
        edit table method
        this method checks if table was chosen from combo box 1 and initializes new editTable object (editTable's constructor argument is chosen table in comboBox1)
        """
        try:
            current_table = self.__combo_box_1.currentText()
            self.__project_controller.check_removed_table_name(current_table)
            edit_table = EditTableWindow(self.__project_model, current_table)
            edit_table.setModal(True)
            edit_table.exec()
            self.set_combo_box_2()
        except Exception as exception:
            warning = WarningWindow(str(exception))
            warning.setModal(True)
            warning.exec()

    def set_combo_box_2(self):
        """
        set comboBox 2 method
        this method adds rows from chosen table to comboBox2
        """
        try:
            table_name = self.__combo_box_1.currentText()
            index = len(self.__combo_box_2) - 1
            while (index > 0):
                self.__combo_box_2.removeItem(index)
                index = index - 1
            for index in range(
                    self.__project_model.get_table_number_of_rows(table_name)):
                self.__combo_box_2.addItem(
                    str(self.__project_model.get_table_row(table_name, index)))

            self.button_1.setEnabled(True)
            self.button_3.setEnabled(True)
            self.button_5.setEnabled(True)
            self.button_7.setEnabled(True)

        except Exception:

            self.button_1.setEnabled(False)
            self.button_3.setEnabled(False)
            self.button_5.setEnabled(False)
            self.button_7.setEnabled(False)

    def combo_box_2_changed(self):
        """
        combo box 2 changed method
        this method adjusts combo box 2 size to current row size
        :return:
        """
        if self.__combo_box_2.currentText() == 'Wybierz rekord':
            self.__combo_box_2.move(400, 175)
            self.__combo_box_2.setFixedSize(100, 20)
            self.__combo_box_2.adjustSize()
            self.button_2.setEnabled(False)
            self.button_4.setEnabled(False)
        else:
            self.__combo_box_2.move(
                500 - (len(self.__combo_box_2.currentText()) + 5) * 5, 175)
            self.__combo_box_2.setFixedSize(
                (len(self.__combo_box_2.currentText()) + 5) * 5, 20)
            print(self.__combo_box_2.currentText())
            print(len(self.__combo_box_2.currentText()))
            self.__combo_box_2.adjustSize()
            self.button_2.setEnabled(True)
            self.button_4.setEnabled(True)

    def create_table(self):
        """
        create table method
        this method initializes new AddTable object and adds table name to combo box 1
        """
        try:
            add_table = AddTableWindow(self.__project_model)
            add_table.setModal(True)
            add_table.exec()
            self.__project_controller.check_table_name(
                add_table.get_table_name())
            self.__combo_box_1.addItem(add_table.get_table_name())
        except Exception as exception:
            print(exception)

    def add_row(self):
        """
        Add row method
        this method checks if table was chosen from combo box 1 and initializes new Add row window object (if table is chosen)
        """
        try:
            current_table = self.__combo_box_1.currentText()
            self.__project_controller.check_removed_table_name(current_table)
            add_row_window = AddRowWindow(self.__project_model, current_table)
            add_row_window.setModal(True)
            add_row_window.exec()
            self.set_combo_box_2()
        except Exception as exception:
            warning = WarningWindow(str(exception))
            warning.setModal(True)
            warning.exec()

    def remove_table(self):
        """
        Remove table method
        this method checks if table was chosen from combo box 1 and initializes new ConfirmRemoveTableWindow object
        """
        try:
            table_name = self.__combo_box_1.currentText()
            self.__project_controller.check_removed_table_name(table_name)
            confirm = ConfirmRemoveTableWindow(self.__project_model,
                                               self.__combo_box_1, table_name)
            confirm.setModal(True)
            confirm.exec()

        except Exception as exception:
            warning = WarningWindow(str(exception))
            warning.setModal(True)
            warning.exec()
class Cancel_record(QMainWindow):
    def __init__(self, *args):
        super().__init__()
        self.initUI(args)
        self.con = sqlite3.connect('m_base.db')

    def initUI(self, args):
        self.setGeometry(100, 100, 550, 400)
        self.setWindowTitle('Отмена записи')

        self.edit_cancel_snils = QLineEdit(self)
        self.edit_cancel_snils.move(300, 70)

        self.btn_back = QPushButton(u'\u27F5', self)
        self.btn_back.setFocus()
        self.btn_back.move(10, 5)
        self.btn_back.clicked.connect(self.back)

        self.lbl_cancel_snils = QLabel(self)
        self.lbl_cancel_snils.setText('Введите СНИЛС')
        self.lbl_cancel_snils.move(150, 75)
        self.lbl_cancel_snils.adjustSize()

        self.btn_get_rec = QPushButton('Получить доступные записи', self)
        self.btn_get_rec.move(200, 150)
        self.btn_get_rec.adjustSize()
        self.btn_get_rec.clicked.connect(self.get_info)

        self.record_widget = QComboBox(self)
        self.record_widget.move(200, 220)

        self.btn_ok_cancel = QPushButton('Подтвердить отмену', self)
        self.btn_ok_cancel.move(215, 300)
        self.btn_ok_cancel.adjustSize()
        self.btn_ok_cancel.clicked.connect(self.ok_cancel)

        self.lbl_info_cancel = QLabel(self)
        self.lbl_info_cancel.setText('Запись еще не отменена')
        self.lbl_info_cancel.setStyleSheet("color: #8B0000")
        self.lbl_info_cancel.move(210, 350)
        self.lbl_info_cancel.adjustSize()

    def get_info(self):
        if self.edit_cancel_snils.text():
            self.cur = self.con.cursor()
            m_list = self.cur.execute(
                """SELECT date, time, doctors_name FROM registered_patients, doctors
                          WHERE registered_patients.snils = ?  AND registered_patients.doctors_id = doctors.doctors_id""",
                (int(self.edit_cancel_snils.text()), )).fetchall()
            record_list = []
            for el in m_list:
                d, m, y = map(int, el[0].split('.'))
                if dt.date(y, m, d) > dt.date.today():
                    data, time, doctor = el
                    record_list.append(f'{data} {time} {doctor}')
            self.record_widget.addItems(record_list)
            self.record_widget.adjustSize()
        else:
            self.lbl_info_cancel.setFont(QFont("Source Serif Pro Semibold",
                                               12))
            self.edit_cancel_snils.setStyleSheet("background-color: #FF0000")

    def keyPressEvent(self, event):
        if event.key() == QtCore.Qt.Key_Backspace:
            self.back()

    def back(self):
        self.welcome_form = Welcome_form()
        self.welcome_form.show()
        self.hide()

    def ok_cancel(self):
        choose_for_cancel = self.record_widget.currentText()
        date, time, *doctor = choose_for_cancel.split()
        id_record = self.cur.execute(
            """SELECT id FROM registered_patients, doctors
                                  WHERE registered_patients.snils = ? AND registered_patients.date = ? AND registered_patients.time = ? AND registered_patients.doctors_id = doctors.doctors_id""",
            (int(self.edit_cancel_snils.text()), date, time)).fetchone()

        self.cur.execute("DELETE FROM registered_patients WHERE id = ?",
                         (id_record[0], ))
        self.con.commit()
        self.cur.execute(
            "UPDATE reception_date_time SET free = 1 WHERE date_work = ? AND time = ? AND doctors_id = "
            "(SELECT doctors_id FROM doctors WHERE doctors_name LIKE ?)",
            (date, time, ' '.join(doctor)))
        self.con.commit()
        self.lbl_info_cancel.setText('Запись отменена!')
        self.lbl_info_cancel.setStyleSheet("color: #32CD32")
Example #18
0
class mainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.flag=0
        #自己输入式子按下“确定”按钮会将题目用火柴棍显示,并显示答案
        confrim_btn = QPushButton('确定', self)
        confrim_btn.move(285, 355)
        confrim_btn.resize(135,35)

        #自己输入式子按下“出题”按钮会将题目用火柴棍显示,但不会显示答案
        question_btn=QPushButton('出题',self)
        question_btn.move(50,355)
        question_btn.resize(135,35)

        #输入式子的第一个数字
        self.num_a = QLineEdit(self)
        self.num_a.resize(70,50)
        self.num_a.setFont(QFont( "微软雅黑" , 20 ))
        self.num_a.move(50,290)

        #输入式子的运算符
        self.operator = QComboBox(self)
        self.operator.resize(70,50)
        self.operator.setFont(QFont("微软雅黑", 15))
        self.operator.move(138,292)
        self.operator.addItems(['+', '-', '*'])
        self.operator.adjustSize()

        #输入式子的第二个数字
        self.num_b = QLineEdit(self)
        self.num_b.resize(70, 50)
        self.num_b.setFont(QFont("微软雅黑", 20))
        self.num_b.move(210,290)

        label_equal = QLabel(self)
        label_equal.setText("=")
        label_equal.move(280,270)
        label_equal.setFont(QFont("微软雅黑",30))
        label_equal.adjustSize()

        #输入式子的结果
        self.num_c = QLineEdit(self)
        self.num_c.resize(90, 50)
        self.num_c.setFont(QFont("微软雅黑", 20))
        self.num_c.move(330,290)

        #显示答案
        self.text_result=QTextBrowser(self)
        self.text_result.move(470,300)
        self.text_result.resize(480,250)
        self.text_result.setFont(QFont("微软雅黑", 20))

        label_equal = QLabel(self)
        label_equal.setText("解答")
        label_equal.move(680, 245)
        label_equal.setFont(QFont("微软雅黑", 13))
        label_equal.adjustSize()

        label_make_question = QLabel(self)
        label_make_question.setText("自己出题")
        label_make_question.move(180, 235)
        label_make_question.setFont(QFont("微软雅黑", 13))
        label_make_question.adjustSize()

        label_choose_question = QLabel(self)
        label_choose_question.setText("从题库选题")
        label_choose_question.move(165, 415)
        label_choose_question.setFont(QFont("微软雅黑", 13))
        label_choose_question.adjustSize()

        level_label=QLabel(self)
        level_label.setFont(QFont("微软雅黑", 10))
        level_label.move(50, 465)
        level_label.setText('等级:')
        level_label.adjustSize()

        #选择等级
        self.level=QComboBox(self)
        self.level.addItems(['1','2','3'])
        self.level.setFont(QFont("微软雅黑", 10))
        self.level.move(100,465)
        self.level.currentIndexChanged.connect(self.levelChanged)
        self.level.resize(135, 35)

        #从题库中选择一题,显示该题答案
        answer_btn = QPushButton('显示答案', self)
        answer_btn.move(100, 510)
        answer_btn.resize(135, 35)

        #显示题库上一题
        former_btn = QPushButton('上一题', self)
        former_btn.move(285, 465)
        former_btn.resize(135, 35)

        #显示题库下一题
        latter_btn = QPushButton('下一题', self)
        latter_btn.move(285, 510)
        latter_btn.resize(135, 35)

        confrim_btn.clicked.connect(self.confirm_btn_clicked)
        question_btn.clicked.connect(self.question_btn_clicked)
        answer_btn.clicked.connect(self.answer)
        former_btn.clicked.connect(self.former_btn_clicked)
        latter_btn.clicked.connect(self.latter_btn_clicked)

        self.numbers=[QPixmap('new_0.png'),QPixmap('new_1.png'),QPixmap('new_2.png'),QPixmap('new_3.png'),
                      QPixmap('new_4.png'),QPixmap('new_5'),QPixmap('new_6.png'),QPixmap('new_7.png'),
                      QPixmap('new_8.png'),QPixmap('new_9.png'),QPixmap('new_add.png'),QPixmap('new_minus.png'),
                      QPixmap('new_mul.png'),QPixmap('new_equal.png')]

        #以下为题库,每一等级有10道题,Order表示目前显示的是第几题
        self.Order=0
        OneMatchProblem1 = [['5', '2', '8', '+'], ['1', '5', '4', '+'],['7','8','7','-'],['8','2','-4','+'],['0','3','2','+'],['5','1','8','-'],
                            ['3','7','4','-'],['6','9','5','+'],['4','5','7','+'],['5','5','8','+']]
        OneMatchProblem2 = [['21', '52', '83', '+'], ['22','45','97','+'],['12','35','45','+'],['15','23','62','-'],['41','72','35','-'],
                            ['68','12','12','+'],['-31','10','-87','+'],['77','51','34','-'],['77','51','34','+'],['85', '98', '181', '-']]
        OneMatchProblem3 = [['8', '4', '35', '*'], ['31', '90', '4550', '*'],['16','86','1230','*'],['98','32','1056','*'],['68','2','204','*'],
                            ['55','90','5398','*'],['85','5','255','*'],['52','11','3892','*'],['8','22','190','*'],['8','80','784','*']]

        TwoMatchProblem1 = [['4', '3', '2', '+'], ['8', '2', '-8', '-'],['-4','2','-8','+'],['0','4','7','+'],['0','1','-7','-'],['5','1','-7','-'],
                            ['5','1','-4','+'],['2','1','7','+'],['2','4','0','+'],['5','4','0','-']]
        TwoMatchProblem2 = [['52', '44', '53', '-'], ['65', '34', '42', '+'],['-57','11','-80','+'],['-27','31','60','-'],['32','36','-41','-'],
                            ['-60','59','21','-'],['81','53','121','+'],['90','53','121','-'],['90','31','30','+'],['34','31','30','+']]
        TwoMatchProblem3 = [['-99', '99', '6881', '*'], ['94', '69', '4704', '*'],['-56','96','4376','*'],['15','27','7515','*'],['15','27','7515','*'],
                            ['62','69','3276','*'],['71','6','439','*'],['23','12','276','+'],['8','33','-104','*'],['-84','50','-4072','*']]
        #等式题库
        AccurateProblem = [['6', '0', '6', '+'], ['9', '0', '9', '+'], ['2', '3', '5', '+'],
                            ['9', '8', '17', '+'], ['1', '8', '9', '+'],
                            ['1', '3', '4', '+'], ['1', '3', '3', '*'], ['2', '3', '6', '*'],
                            ['5', '3', '2', '-'], ['5', '1', '4', '-']]

        self.Problems=[[OneMatchProblem1,OneMatchProblem2,OneMatchProblem3],[TwoMatchProblem1,TwoMatchProblem2,TwoMatchProblem3,AccurateProblem]]
        self.levels=0

        #var0,var1...var11为火柴棍图片显示的Label
        for i in range(12):
            exec('self.var{}=QLabel(self)'.format(i))

        if(self.flag==0):
            self.equation = OneMatchProblem1[0]
        else:
            self.equation=TwoMatchProblem1[0]

        self.setNum()
        self.setGeometry(300, 300, 1000, 600)

    #分割线
    def paintEvent(self, e):
        qp = QPainter()
        qp.begin(self)
        self.drawLines(qp)
        qp.end()

    def drawLines(self, qp):
        pen = QPen(Qt.black, 2, Qt.SolidLine)

        pen.setStyle(Qt.DotLine)
        qp.setPen(pen)
        qp.drawLine(50, 220, 950, 220)

        pen.setStyle(Qt.DotLine)
        qp.setPen(pen)
        qp.drawLine(50, 405, 420, 405)

    windowList=[]
    def closeEvent(self,event):
        George=IntroWindow()
        self.windowList.append(George)
        George.show()
        event.accept()

    def levelChanged(self):
        if(self.level.currentText()!='等式题库'):
            self.levels=int(self.level.currentText())-1
        else:
            self.levels=3
        self.Order=0
        self.equation=self.Problems[self.flag][self.levels][0]
        self.setNum()

    #判断输入的式子是否符合要求
    def getNum(self):
        self.equation[0] = self.num_a.text()
        self.equation[1] = self.num_b.text()
        self.equation[2] = self.num_c.text()
        self.equation[3] = self.operator.currentText()
        a=self.equation
        len1 = len(self.equation[0])
        len2 = len(self.equation[1])
        len3 = len(self.equation[2])
        if (len1 == 0 or (a[0][0]=='-' and (len1>3 or a[0][1:].isdigit()==False)) or (a[0][0]!='-' and (len1 > 2 or a[0].isdigit()==False)) ):
            return False
        elif(len2 == 0 or len2 > 2 or a[1].isdigit()==False ):
            return False
        elif(int(a[1])<0):
            return False
        elif(len3 == 0 or (a[2][0]=='-' and (len3>5 or a[2][1:].isdigit()==False)) or (a[2][0]!='-' and (len3 > 4 or a[2].isdigit()==False))):
            return False
        else:
            return True

    def confirm_btn_clicked(self):
        if (self.getNum() == False):
            QMessageBox.warning(self, "警告", "式子不符合规范,请重新输入式子", QMessageBox.Yes | QMessageBox.No)
        else:
            self.setNum()
            self.answer()

    def former_btn_clicked(self):
        if(self.Order==0):
            QMessageBox.warning(self, "警告", "已翻到第一题", QMessageBox.Yes | QMessageBox.No)
        else:
            self.Order-=1
            self.equation=self.Problems[self.flag][self.levels][self.Order]
        self.setNum()

    def latter_btn_clicked(self):
        if(self.Order==9):
            QMessageBox.warning(self, "警告", "已翻到最后一题", QMessageBox.Yes | QMessageBox.No)
        else:
            self.Order+=1
            self.equation=self.Problems[self.flag][self.levels][self.Order]
        self.setNum()

    #调用search函数得到答案
    def answer(self):
        ans = ''
        #若移动两根火柴
        if (self.flag == 1):
            self.result = search2.make_equation2(self.equation)
            n = int(len(self.result) / 12)
            if(n!=0):
                ans = ans + '移动2根火柴:\n'
            for i in range(n):
                ans=ans+str(self.result[i * 12 + 10])
                for j in range(2):
                    ans = ans + str(self.result[i * 12 + j])
                ans = ans + str(self.result[i * 12 + 8])
                for j in range(2, 4):
                    ans = ans + str(self.result[i * 12 + j])
                ans = ans + str(self.result[i * 12 + 9])
                ans = ans + str(self.result[i * 12 + 11])
                for j in range(4, 8):
                    ans = ans + str(self.result[i * 12 + j])
                ans = ans + '\n'
        #若移动一根火柴
        self.result = search.make_equation(self.equation)
        if (self.flag == 1 and self.result != []):
            ans = ans + '移动1根或0根火柴:\n'
        n = int(len(self.result) / 11)
        for i in range(n):
            for j in range(3):
                ans = ans + str(self.result[i * 11 + j])
            ans = ans + str(self.result[i * 11 + 10])
            for j in range(3, 5):
                ans = ans + str(self.result[i * 11 + j])
            if (self.result[i * 11 + 10] == '='):
                ans = ans + '-'
            else:
                ans = ans + '='
            for j in range(5, 10):
                ans = ans + str(self.result[i * 11 + j])
            ans = ans + '\n'

        if (ans == ''):
            self.text_result.setText('该式子无解')
        else:
            self.text_result.setText(ans)

    def question_btn_clicked(self):
        if (self.getNum() == False):
            QMessageBox.warning(self, "警告", "式子不符合规范,请重新输入式子", QMessageBox.Yes | QMessageBox.No)
        else:
            self.setNum()

    #将式子用火柴棍显示出来
    def setNum(self):
        equa=''
        equa+=self.equation[0]
        equa+=self.equation[3]
        equa+=self.equation[1]
        equa+='='
        equa+=self.equation[2]
        for i in range(12):
            exec('self.var{}.clear()'.format(i))
        for i in range(len(equa)):
            if (equa[i] == '+'):
                exec('self.var{}.setPixmap(self.numbers[10])'.format(i))
                exec('self.var{}.resize(60,60)'.format(i))
                exec('self.var{}.move(75*i+50,75)'.format(i))
            elif(equa[i]=='-'):
                exec('self.var{}.setPixmap(self.numbers[11])'.format(i))
                exec('self.var{}.resize(60,60)'.format(i))
                exec('self.var{}.move(75*i+50,75)'.format(i))
            elif (equa[i] == '*'):
                exec('self.var{}.setPixmap(self.numbers[12])'.format(i))
                exec('self.var{}.resize(60,60)'.format(i))
                exec('self.var{}.move(75*i+50,75)'.format(i))
            elif (equa[i] == '='):
                exec('self.var{}.setPixmap(self.numbers[13])'.format(i))
                exec('self.var{}.resize(60,60)'.format(i))
                exec('self.var{}.move(75*i+50,75)'.format(i))
            else:
                exec('self.var{}.setPixmap(self.numbers[int(equa[i])])'.format(i))
                exec('self.var{}.resize(75,120)'.format(i))
                exec('self.var{}.move(75*i+50,50)'.format(i))

            exec('self.var{}.setScaledContents(True)'.format(i))
class MainGrid(QGridLayout):
    def __init__(self, window):
        super().__init__()
        self.window = window
        self.service = func()
        self.lists = ret_lists(self.service)
        self.list_idx = 0
        self.completed = QPushButton("Show completed")
        self.deleted = QPushButton("Show deleted")
        self.tasks = []
        self.completed_tasks = []
        self.drop_list = QComboBox()
        self.text_box = QLineEdit()
        self.reload = QPushButton("Reload")
        self.add_button = QPushButton("Add")
        self.drop_list.adjustSize()
        self.text_box.returnPressed.connect(self.add_task)
        self.add_button.clicked.connect(self.add_task)
        self.reload.clicked.connect(self.update_tasks)
        self.addWidget(self.drop_list, 0, 0)
        self.addWidget(self.reload, 0, 1)
        self.addWidget(self.text_box, 1, 0)
        self.addWidget(self.add_button, 1, 1)
        for i in self.lists:
            self.drop_list.addItem(i[0])
        self.drop_list.currentIndexChanged.connect(self.selectionchange)
        self.completed.clicked.connect(self.show_completed)
        self.deleted.clicked.connect(self.show_deleted)
        self.update_tasks()
        self.setColumnStretch(0, 1)
        # self.resizeColumnsToContents()

    def selectionchange(self, i):
        self.reload_button(i)
        self.update_tasks()

    def add_task(self):
        new_task = {
            "status": "needsAction",
            "kind": "tasks#task",
            # "updated": "A String", # Last modification time of the task (as a RFC 3339 timestamp).
            "title": self.text_box.text(),
            # "etag": "A String", # ETag of the resource.
            # "position": "A String",
        }
        add(self.lists[self.list_idx][1], new_task, self.service)
        self.text_box.clear()
        self.update_tasks()

    def update_tasks(self):
        self.tasks = ret_tasks(self.lists[self.list_idx][1], self.service)
        for i in reversed(range(4, self.count())):
            self.itemAt(i).widget().setParent(None)

        for cnt, i in enumerate(self.tasks):
            label = QLabel(i[0])
            label.setWordWrap(True)
            label.setFont(QFont('Arial', 14))
            self.addWidget(label, cnt + 2, 0)
            x = QPushButton("Delete")
            y = QPushButton("Complete")
            self.addWidget(x, cnt + 2, 1)
            self.addWidget(y, cnt + 2, 2)
            x.clicked.connect(partial(self.delete_button, cnt))
            y.clicked.connect(partial(self.complete_button, cnt))
        self.addWidget(self.completed, 2 + len(self.tasks), 0)
        self.addWidget(self.deleted, 2 + len(self.tasks), 1)

    def show_completed(self):
        self.completed_tasks = ret_tasks(self.lists[self.list_idx][1],
                                         self.service, True)
        height = 2 + len(self.tasks) + 1
        for i in reversed(range(4 + (len(self.tasks)) * 3 + 2, self.count())):
            self.itemAt(i).widget().setParent(None)
        for cnt, i in enumerate(self.completed_tasks):
            label = QLabel(i[0])
            label.setWordWrap(True)
            label.setFont(QFont('Arial', 14))
            self.addWidget(label, height + cnt, 0)
            x = QPushButton("Restore")
            self.addWidget(x, height + cnt, 1)
            x.clicked.connect(partial(self.restore_button, cnt, 'completed'))

    def show_deleted(self):
        self.deleted_tasks = ret_tasks(self.lists[self.list_idx][1],
                                       self.service, False, True)
        height = 2 + len(self.tasks) + 1
        for i in reversed(range(4 + (len(self.tasks)) * 3 + 2, self.count())):
            self.itemAt(i).widget().setParent(None)
        for cnt, i in enumerate(self.deleted_tasks):
            label = QLabel(i[0])
            label.setWordWrap(True)
            label.setFont(QFont('Arial', 14))
            self.addWidget(label, height + cnt, 0)
            x = QPushButton("Restore")
            self.addWidget(x, height + cnt, 1)
            x.clicked.connect(partial(self.restore_button, cnt, 'deleted'))

    def reload_button(self, i):
        self.list_idx = i

    def restore_button(self, idx, task_type):
        if (task_type == 'completed'):
            restore(self.lists[self.list_idx][1], self.completed_tasks[idx][1],
                    self.completed_tasks[idx][2], self.service)
        elif (task_type == 'deleted'):
            restore(self.lists[self.list_idx][1], self.deleted_tasks[idx][1],
                    self.deleted_tasks[idx][2], self.service)
        self.update_tasks()

    def delete_button(self, idx):
        reply = QMessageBox.question(self.window,'Quit', 'Are you sure you want to delete?',\
            QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if (reply == QMessageBox.Yes):
            delete(self.lists[self.list_idx][1], self.tasks[idx][1],
                   self.service)
            self.update_tasks()

    def complete_button(self, idx):
        complete(self.lists[self.list_idx][1], self.tasks[idx][1],
                 self.tasks[idx][2], self.service)
        self.update_tasks()
Example #20
0
class App(QMainWindow):
    def __init__(self, config):
        super(App, self).__init__()
        super().__init__()
        self.tasks = [{
            "Munkavállaló,\nmegbízottszemély neve/\nbeosztása": "HR"
        }, {
            "Bruttó bér/ illetmény/ megbízási díj/ céljuttatás":
            "Bruttó bér"
        }, {
            "Bruttó bér projektre elszámolva":
            "Programban elsz bér (54)"
        }, {
            "Járulékok és adók": "Kapcsolódó járulék (56)"
        }]
        self.task1_checkbox = QCheckBox(
            "Task1: " + next(iter(self.tasks[0].keys())).replace('\n', '') +
            ' -> ' + next(iter(self.tasks[0].values())), self)
        self.task2_checkbox = QCheckBox(
            "Task2: " + next(iter(self.tasks[1].keys())).replace('\n', '') +
            ' -> ' + next(iter(self.tasks[1].values())), self)
        self.task3_checkbox = QCheckBox(
            "Task3: " + next(iter(self.tasks[2].keys())).replace('\n', '') +
            ' -> ' + next(iter(self.tasks[2].values())), self)
        self.task4_checkbox = QCheckBox(
            "Task4: " + next(iter(self.tasks[3].keys())).replace('\n', '') +
            ' -> ' + next(iter(self.tasks[3].values())), self)
        self.task_checks = [True, True, True, True]
        self.title = 'Vax'
        self.left = 300
        self.top = 300
        self.width = 700
        self.height = 600
        self.logTextBox = None
        self.excel_processor = None
        try:
            self.mean = str(config['measurements']['mean'])
        except:
            self.mean = '0'
        try:
            self.sample_size = str(config['measurements']['sample-size'])
        except:
            self.sample_size = '0'
        try:
            default_full_label = config['sources']['full']
        except:
            default_full_label = no_file_selected
        try:
            default_terv_label = config['sources']['terv']
        except:
            default_terv_label = no_file_selected
        try:
            default_target_color_label = config['color']
        except:
            default_target_color_label = PINK
        self.full_label = QLabel(default_full_label, self)
        self.terv_label = QLabel(default_terv_label, self)
        self.target_color_label = QLabel(default_target_color_label, self)
        self.init_ui()
        logging.info(random.choice(welcome))
        logging.info(random.choice(comment) + ' ' + random.choice(fun))

    def init_ui(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.full_button()
        self.terv_button()
        self.color_button()
        self.month_dropdown()
        self.year_dropdown()
        self.match_button()
        self.task_checkboxes()
        self.logger()
        self.log_cleaner()
        self.show()

    def full_button(self):
        full_button = QPushButton('Full', self)
        full_button.move(20, 20)
        full_button.resize(80, 20)
        full_button.clicked.connect(self.load_full)
        self.full_label.move(120, 25)

    def terv_button(self):
        terv_button = QPushButton('HR terv', self)
        terv_button.move(20, 60)
        terv_button.resize(80, 20)
        terv_button.clicked.connect(self.load_terv)
        self.terv_label.move(120, 65)

    def match_button(self):
        match_button = QPushButton('Összevet', self)
        match_button.move(20, 130)
        match_button.resize(100, 80)
        match_button.clicked.connect(self.match)

    def month_dropdown(self):
        comboBox = QComboBox(self)
        comboBox.resize(80, 20)
        self.months = [
            "Január", "Február", "Március", "Április", "Május", "Június",
            "Július", "Augusztus", "Szeptember", "Október", "November",
            "December"
        ]
        comboBox.addItems(self.months)
        month_index = datetime.today().month - 2 if datetime.today(
        ).month >= 2 else 11
        self.selected_month = self.months[month_index]
        comboBox.setCurrentIndex(month_index)
        comboBox.move(21, 100)
        comboBox.activated[str].connect(self.select_month)

    def year_dropdown(self):
        self.year_combo = QComboBox(self)
        years = [str(datetime.today().year), str(datetime.today().year - 1)]
        self.year_combo.addItems(years)
        self.selected_year = years[0]
        self.year_combo.setCurrentIndex(0)
        self.year_combo.move(110, 100)
        self.year_combo.activated[str].connect(self.select_year)

    def color_button(self):
        color_button = QPushButton('Szín', self)
        color_button.move(180, 100)
        color_button.resize(80, 20)
        color_button.clicked.connect(self.load_color)
        self.target_color_label.move(270, 95)
        self.target_color_label.setStyleSheet('QLabel {color: #' +
                                              self.target_color_label.text() +
                                              ';}')

    def select_month(self, month):
        self.selected_month = month
        logging.debug("Kiválasztott hónap: " + month)

    def select_year(self, year):
        self.selected_year = year
        logging.debug("Kiválasztott év: " + year)

    def task_checkboxes(self):
        self.task1_checkbox.move(140, 130)
        self.task1_checkbox.stateChanged.connect(self.task1_update_state)
        self.task1_checkbox.resize(400, 20)
        self.task1_checkbox.setChecked(True)

        self.task2_checkbox.move(140, 150)
        self.task2_checkbox.stateChanged.connect(self.task2_update_state)
        self.task2_checkbox.resize(400, 20)
        self.task2_checkbox.setChecked(True)

        self.task3_checkbox.move(140, 170)
        self.task3_checkbox.stateChanged.connect(self.task3_update_state)
        self.task3_checkbox.resize(400, 20)
        self.task3_checkbox.setChecked(True)

        self.task4_checkbox.move(140, 190)
        self.task4_checkbox.stateChanged.connect(self.task4_update_state)
        self.task4_checkbox.resize(400, 20)
        self.task4_checkbox.setChecked(True)

    def task1_update_state(self):
        self.task1_check_state = self.task1_checkbox.isChecked()
        self.task_checks[0] = self.task1_checkbox.isChecked()
        if self.task1_checkbox.isChecked():
            logging.debug('Task 1 végrehajtása bekapcsolva.')
        else:
            logging.debug('Task 1 végrehajtása kikapcsolva.')

    def task2_update_state(self):
        self.task2_check_state = self.task2_checkbox.isChecked()
        self.task_checks[1] = self.task2_checkbox.isChecked()
        if self.task2_checkbox.isChecked():
            logging.debug('Task 2 végrehajtása bekapcsolva.')
        else:
            logging.debug('Task 2 végrehajtása kikapcsolva.')

    def task3_update_state(self):
        self.task3_check_state = self.task3_checkbox.isChecked()
        self.task_checks[2] = self.task3_checkbox.isChecked()
        if self.task3_checkbox.isChecked():
            logging.debug('Task 3 végrehajtása bekapcsolva.')
        else:
            logging.debug('Task 3 végrehajtása kikapcsolva.')

    def task4_update_state(self):
        self.task4_check_state = self.task4_checkbox.isChecked()
        self.task_checks[3] = self.task4_checkbox.isChecked()
        if self.task4_checkbox.isChecked():
            logging.debug('Task 4 végrehajtása bekapcsolva.')
        else:
            logging.debug('Task 4 végrehajtása kikapcsolva.')

    @pyqtSlot()
    def load_color(self):
        color = QColorDialog.getColor()
        if color.name() == '#000000':
            return
        logging.debug('Szín kiválasztva: ' + color.name()[1:])
        self.target_color_label.setText(color.name()[1:])
        self.target_color_label.setStyleSheet('QLabel {color: #' +
                                              self.target_color_label.text() +
                                              ';}')
        self.write_out()

    @pyqtSlot()
    def load_full(self):
        full_file = QFileDialog.getOpenFileName()[0]
        if not full_file:
            return
        logging.debug('FULL fájl kiválasztva: ' + full_file)
        file_name = full_file if os.path.isfile(
            full_file) else no_file_selected
        self.full_label.setText(file_name)
        self.full_label.adjustSize()
        self.write_out()

    @pyqtSlot()
    def load_terv(self):
        terv_file = QFileDialog.getOpenFileName()[0]
        if not terv_file:
            return
        logging.debug('HR terv fájl kiválasztva: ' + terv_file)
        file_name = terv_file if os.path.isfile(
            terv_file) else no_file_selected
        self.terv_label.setText(file_name)
        self.terv_label.adjustSize()
        self.write_out()

    @pyqtSlot()
    def match(self):
        if not os.path.isfile(self.terv_label.text()):
            logging.error("Nem sikerült betölteni a terv fájlt: '" +
                          self.terv_label.text() + "'")
            return
        if not os.path.isfile(self.full_label.text()):
            logging.error("Nem sikerült betölteni a FULL fájlt: '" +
                          self.terv_label.text() + "'")
            return
        logging.info('Excel táblák összevetése...')
        started_at = datetime.now()
        self.excel_processor = ExcelProcessor(
            self, self.terv_label.text(), self.full_label.text(),
            self.selected_year, self.selected_month,
            self.months.index(self.selected_month) + 1, self.mean,
            self.target_color_label.text(), self.checked_tasks())
        finished_at = datetime.now()
        self.took_seconds = str((finished_at - started_at).total_seconds())
        logging.info('Ennyi másodpercig tartott a teljes feldolgozás: ' +
                     str(format(float(self.took_seconds), '.2f')))
        self.calculate_new_mean()
        self.write_out()
        self.app_log_outro(self.excel_processor.error_cells)
        self.excel_processor = None

    @pyqtSlot()
    def clean_logs(self):
        self.logTextBox.clear()

    def resizeEvent(self, event):
        if self.logTextBox:
            self.logTextBox.resize(event.size().width(), event.size().height())
        self.full_label.adjustSize()
        self.terv_label.adjustSize()
        self.year_combo.adjustSize()
        return super(App, self).resizeEvent(event)

    def write_out(self):
        f = open('config.yml', 'w')
        f.write("sources:\n")
        f.write("  full: " + self.full_label.text() + "\n")
        f.write("  terv: " + self.terv_label.text() + "\n")
        f.write("measurements:\n")
        f.write("  sample-size: " + self.sample_size + "\n")
        f.write("  mean: " + self.mean + "\n")
        f.write("color: " + self.target_color_label.text() + "\n")
        f.close()

    def log_cleaner(self):
        log_cleaner_button = QPushButton('Log ürítése', self)
        log_cleaner_button.move(611, 170)
        log_cleaner_button.resize(70, 22)
        log_cleaner_button.clicked.connect(self.clean_logs)

    def logger(self):
        combo_box = QComboBox(self)
        combo_box.resize(60, 20)
        self.log_levels = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
        combo_box.addItems(self.log_levels)
        combo_box.setCurrentIndex(1)
        combo_box.move(620, 195)
        combo_box.activated[str].connect(self.set_log_level)
        log_label = QLabel('Logolási szint: ', self)
        log_label.resize(80, 20)
        log_label.move(550, 195)

        self.logTextBox = QTextEditLogger(self, self.width, self.height, 220)
        self.logTextBox.setFormatter(
            logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
        logging.getLogger().addHandler(self.logTextBox)
        logging.getLogger().setLevel(logging.INFO)

    def set_log_level(self, log_level):
        logging.debug('Új log szint került beállításra: ' + log_level)
        logging.getLogger().setLevel(log_level_map.get(log_level))

    def calculate_new_mean(self):
        try:
            self.mean = str(
                (float(self.mean) * float(self.sample_size) +
                 float(self.took_seconds)) / (float(self.sample_size) + 1))
            self.sample_size = str(float(self.sample_size) + 1)
        except:
            return

    def app_log_outro(self, failed_verification_cells):
        if len(failed_verification_cells) == 0:
            Message.log_block(
                random.choice(fun) + random.choice(fun) +
                ' A teljes végrehajtással sikeresen végeztünk!' +
                random.choice(fun) + random.choice(fun),
                "Ennyi másodpercig tartott: " +
                Time.format_seconds(self.took_seconds), logging.critical)
        else:
            Message.log_block(
                random.choice(sad) +
                ' Végeztünk mindennel, de voltak FULL-beli cellák amik nem egyeztek: '
                + str(failed_verification_cells),
                "Ennyi másodpercig tartott: " +
                Time.format_seconds(self.took_seconds), logging.critical)

    def closeEvent(self, event):
        if self.excel_processor is not None:
            self.excel_processor.close()

    def checked_tasks(self):
        checked_tasks_listed = []
        for i in range(4):
            if self.task_checks[i]:
                checked_tasks_listed.append(self.tasks[i])
            else:
                checked_tasks_listed.append(None)
        return checked_tasks_listed
Example #21
0
class SetinView(QDialog):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.nusubut = QPushButton('确定', self)
        self.nusubut.clicked.connect(self.Sure)
        self.nusubut.resize(self.nusubut.sizeHint())

        self.submitbut = QPushButton('提交', self)
        self.submitbut.clicked.connect(self.Submit)
        self.submitbut.resize(self.submitbut.sizeHint())
        self.submitbut.setEnabled(False)

        self.setGeometry(400, 400, 300, 150)
        label1=QLabel("请输入学号:")
        label2=QLabel("请选择单位:")
        self.label3=QLabel(self) #Label3
        self.number = QLineEdit(self)
        self.combobox = QComboBox(self)
        self.setWindowTitle("录入")

        setinLayout = QGridLayout()
        setinLayout.addWidget(label1,1,0)
        setinLayout.addWidget(self.label3,0,1)
        setinLayout.addWidget(label2,2,0)
        setinLayout.addWidget(self.number,1,1)
        setinLayout.addWidget(self.combobox,2,1)
        setinLayout.addWidget(self.nusubut,1,2)
        setinLayout.addWidget(self.submitbut,3,2)
        self.setLayout(setinLayout)

    def Sure(self):
        self.submitbut.setEnabled(False)
        self.studentID = self.number.text()
        select = self.GetWorkplace(self.studentID)
        self.combobox.clear()
        self.combobox.addItem('请选择')
        self.label3.adjustSize()
        for i in range(len(select)):
            self.combobox.addItem(select[i])
        self.combobox.adjustSize()
        if select[0] == '用户不存在' or select[0] == '请联系管理员' or select[0] == '请等待':
            pass
        else:
            self.combobox.activated.connect(self.onActivated)

    def Submit(self):
        #print(self.stuWork)
        #print(self.studenID)
        conn = mysql.connector.connect(user='******', password='******', database='selectwork')
        result = conn.cursor()
        if self.expectNum == self.nowNum:
            result.execute('select sstate from ' + self.values + '_student where sno = %s', (self.studentID, ))
            state = result.fetchall()[0][0]
            if state == 1:
                self.label3.setText('请重新确定')
                self.label3.adjustSize()
            else:
                result.execute('update ' + self.values + '_student set splace = %s where sno = %s', (self.stuWork,self.studentID,))
                conn.commit()
                result.execute('select pyx from ' + self.values + '_place where pname = %s', (self.stuWork, ))
                Pyx = result.fetchall()[0][0]
                result.execute('update ' + self.values + '_place set pyx = %s where pname = %s', (Pyx + 1,self.stuWork, ))
                conn.commit()
                result.execute('update rs_zy set now = %s where zy = %s', (self.nowNum + 1, self.values, ) )
                conn.commit()
                result.execute('update ' + self.values + '_student set sstate = %s where sno = %s', (1,self.studentID, ))
                conn.commit()
            #result.execute('update ' + self.values + '_student set sstate = %s where sno = %s', (self.nowNum,self.studentID,))
            #conn.commit()
                self.label3.setText('提交成功')
                self.label3.adjustSize()
        else:
            result.execute('select sstate from ' + self.values + '_student where sno = %s', (self.studentID, ))
            state = result.fetchall()[0][0]
            if state == 1:
                self.label3.setText('请重新确定')
                self.label3.adjustSize()
            else:
                result.execute('update ' + self.values + '_student set splace = %s where sno = %s', (self.stuWork,self.studentID,))
                conn.commit()
                result.execute('select pyx from ' + self.values + '_place where pname = %s', (self.oldPlace, ))
                Pyx = result.fetchall()[0][0]
                result.execute('update ' + self.values + '_place set pyx = %s where pname = %s', (Pyx - 1,self.oldPlace, ))
                conn.commit()
                result.execute('select pyx from ' + self.values + '_place where pname = %s', (self.stuWork, ))
                Pyx = result.fetchall()[0][0]
                result.execute('update ' + self.values + '_place set pyx = %s where pname = %s', (Pyx + 1,self.stuWork, ))
                conn.commit()
                result.execute('update ' + self.values + '_student set sstate = %s where sno = %s', (1,self.studentID, ))
                conn.commit()
                self.label3.setText('修改成功')
                self.label3.adjustSize()
        result.close()
        conn.close()
        self.submitbut.setEnabled(False)


    def GetWorkplace(self, stuID):
        conn = mysql.connector.connect(user='******', password='******', database='selectwork')
        result = conn.cursor()
        #获取专业名称简写
        result.execute('select zy from xh_zy where xh = %s', (stuID,)) 
        self.values = result.fetchall()
        print(stuID)
        
        #可选项列表
        optional = [] 
        if len(self.values) == 0:
            self.label3.setText('用户不存在')
            self.label3.adjustSize()
            optional.append('用户不存在')
        else:
            self.values = str(self.values[0][0]) #self.values存储当前登录学生专业
            #print(values)
            #根据专业获取当前期待选择学生的排名
            result.execute('select now from rs_zy where zy = %s', (self.values,)) 
            self.expectNum = (result.fetchall())[0][0]
            #根据学号获取当前登录学生的排名
            result.execute('select spm,sstate from ' + self.values + '_student where sno = %s', (stuID,)) 
            self.nowNum,state = (result.fetchall())[0]
            if self.expectNum > self.nowNum + 1:
                optional = ['请联系管理员']
                self.label3.setText('您已提交过,请联系管理员进行修改')
                self.label3.adjustSize()
            elif self.expectNum < self.nowNum:
                optional = ['请等待']
                self.label3.setText('请按排名顺序完成录入')
                self.label3.adjustSize()
            else:
                if self.expectNum == self.nowNum:
                    result.execute('update ' + self.values + '_student set sstate = %s where sno = %s', (0,stuID, ))
                    conn.commit()
                    #获取剩余可选工作单位
                    result.execute('select pname from ' + self.values + '_place where pkx > pyx') 
                    valuesPla = result.fetchall()
                    #根据学号获取学生姓名
                    result.execute('select sname from ' + self.values + '_student where sno = %s', (stuID,))
                    valuesNam = result.fetchall()
                    #显示学生姓名
                    self.label3.setText(bytes.decode(valuesNam[0][0]))
                    self.label3.adjustSize()
                    #填充可选单位列表
                    for i in range(len(valuesPla)):
                        optional.append(bytes.decode(valuesPla[i][0]))
                else:
                    result.execute('update ' + self.values + '_student set sstate = %s where sno = %s', (0,stuID, ))
                    conn.commit()
                    result.execute('select splace from ' + self.values + '_student where sno = %s', (stuID,))
                    self.oldPlace = result.fetchall()[0][0]
                    #获取剩余可选工作单位
                    result.execute('select pname from ' + self.values + '_place where pkx > pyx') 
                    valuesPla = result.fetchall()
                    #根据学号获取学生姓名
                    result.execute('select sname from ' + self.values + '_student where sno = %s', (stuID,))
                    valuesNam = result.fetchall()
                    #显示学生姓名
                    self.label3.setText(bytes.decode(valuesNam[0][0]) + '(修改)')
                    self.label3.adjustSize()
                    #填充可选单位列表
                    for i in range(len(valuesPla)):
                        optional.append(bytes.decode(valuesPla[i][0]))
                    if bytes.decode(self.oldPlace) not in optional:
                        optional.append(bytes.decode(self.oldPlace))
            result.close()
            conn.close()
        return optional

    def onActivated(self, index):
        self.stuWork = self.combobox.itemText(index)
        if self.stuWork == '请选择':
            pass
        else:
            self.submitbut.setEnabled(True)