Esempio n. 1
0
class EditSourceWidget(QWidget):
    """==============================================
    Edit source widget

    @description widget for the source list in edit
    source menu.
    =============================================="""
    def __init__(self, url):
        super().__init__()

        layout = QHBoxLayout()
        layout.setAlignment(Qt.AlignLeft)

        # self: action manage from Controller
        self.url_edit = QLineEdit(url)
        self.url_edit.adjustSize()

        # ----------------------------------------------- test BEGIN
        button_resources_test = [
            "./assets/icons/cross.png", "./assets/icons/app.png",
            "./assets/icons/edit.png"
        ]
        self.del_button = AnimatedButton(button_resources_test)
        # ----------------------------------------------- test END

        self.del_button.setFixedWidth(self.url_edit.height())

        layout.addWidget(self.url_edit)
        layout.addWidget(self.del_button)

        self.setLayout(layout)
Esempio n. 2
0
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        self.setMinimumSize(QSize(320, 140))
        self.setWindowTitle(
            "PyQt Line Edit example (textfield) - pythonprogramminglanguage.com"
        )

        self.nameLabel = QLabel(self)
        self.nameLabel.setText('Name:')
        self.line = QLineEdit(self)

        self.line.move(80, 20)
        self.line.resize(200, 32)
        self.nameLabel.move(20, 20)

        pybutton = QPushButton('OK', self)
        pybutton.clicked.connect(self.clickMethod)
        pybutton.resize(200, 32)
        pybutton.move(80, 60)

    def clickMethod(self):
        print('Your name: ' + self.line.text())

        self.line.adjustSize()
Esempio n. 3
0
    def check_login(self):
        # 验证登录
        user_name = self.username_edit.toPlainText()
        password = self.password_edit.toPlainText()
        row = db.get_user(user_name)
        print(row)
        if row == None or len(row) == 0 or row['password'] != password:
            print("用户名或密码错误", user_name, password)
            dialog = QDialog()
            dialog.adjustSize()  # 随内容自动改变大小
            text = QLineEdit("用户名或密码错误", dialog)  # 添加空间显示提示文字
            text.adjustSize()
            # 设置窗口的属性为ApplicationModal模态,用户只有关闭弹窗后,才能关闭主界面
            dialog.setWindowModality(Qt.ApplicationModal)
            dialog.exec_()  # 阻塞执行,只调用show执行后立马销毁
            return
        level = row['level']
        print("level:", level)
        print("跳转")
        from pages import home
        if level == 1:
            self.homepage = home.HomePage1()
            self.homepage.show()
            # return render_template('index_3.html', content=content)
        elif level == 2:
            # return render_template('index_2.html', content=content)
            self.homepage = home.HomePage2()
            self.homepage.show()
        else:
            self.homepage = home.HomePage3()
            self.homepage.show()
        # self.homepage.show()
        self.close()

        pass
Esempio n. 4
0
class SecondWindow(QWidget):
    def __init__(self, dnac, user, pwd):
        super().__init__()
        self.title = 'path trace'
        self.top = 100
        self.left = 100
        self.width = 500
        self.height = 500
        self.dnac = dnac
        self.user = user
        self.pwd = pwd
        self.main_interface()

    def main_interface(self):

        self.setWindowTitle(self.title)
        self.setGeometry(self.top, self.left, self.height, self.width)
        self.source_port = QLineEdit(self)
        self.source_port.setPlaceholderText('source_port')
        self.source_port.move(100, 100)

        self.des_port = QLineEdit(self)
        self.des_port.setPlaceholderText('des_port')
        self.des_port.move(100, 200)
        self.combo = QComboBox(self)
        self.combo1 = QComboBox(self)
        combo_port = get_device_list(self.dnac, self.user, self.pwd)
        for i in combo_port:
            self.combo.addItem(i)
        self.combo.move(250, 100)
        self.combo.activated[str].connect(self.onchanged)

        for i in combo_port:
            self.combo1.addItem(i)
        self.combo1.move(250, 200)
        self.combo1.activated[str].connect(self.onchanged1)

        btn = QPushButton('Click to path traces', self)
        btn.move(100, 300)
        btn.clicked.connect(self.path_trace)

        self.show()

    def onchanged(self, text):
        self.source_port.setText(text)
        self.source_port.adjustSize()

    def onchanged1(self, text):
        self.des_port.setText(text)
        self.des_port.adjustSize()

    def path_trace(self):
        self.path_trace_window = path_trace_window(self.source_port.text(),
                                                   self.des_port.text())
        self.path_trace_window.show()
class Admin_login(QWidget):
    def __init__(self):
        super().__init__()
        self.top = 100
        self.left = 100
        self.width = 800
        self.height = 500
        self.label1()

    def label1(self):
        self.setWindowTitle("Login")
        self.setGeometry(self.left, self.top, self.width, self.height)

        self.label = QLabel(self)
        self.label.setPixmap(QPixmap("new3.jpg"))

        self.lbl = QLabel(self)
        self.lbl.setFont(QFont('SansSerif', 14))
        self.lbl.setStyleSheet("color: rgb(0,0,255)")
        self.lbl.setStyleSheet("fontName='Times-Italic'")
        self.lbl.setText('Username')
        self.lbl.adjustSize()
        self.lbl.move(50, 50)

        self.line = QLineEdit(self)
        self.line.setFont(QFont('SansSerif', 14))
        self.line.move(200, 50)
        self.line.adjustSize()

        self.lbl = QLabel(self)
        self.lbl.setFont(QFont('Cooper', 14))
        self.lbl.setText('Password')
        self.lbl.adjustSize()
        self.lbl.move(50, 180)

        self.line = QLineEdit(self)
        self.line.setFont(QFont('Cooper', 14))
        self.line.move(200, 180)
        self.line.adjustSize()

        self.pushbutton1 = QPushButton("Login", self)
        self.pushbutton1.setFont(QFont('SansSerif', 14))
        self.pushbutton1.resize(self.pushbutton1.sizeHint())
        self.pushbutton1.move(300, 280)
        self.pushbutton1.clicked.connect(self.linked)

        self.show()

    def linked(self):
        from Weladmin import Voption
        self.Vopt = Voption()
        self.close()
        self.Vopt.show()
        print("login button is clicked")
Esempio n. 6
0
class Login(QWidget):
    def __init__(self):
        super().__init__()
        self.title = 'Login'
        self.top = 100
        self.left = 100
        self.width = 400
        self.height = 400
        self.log_interface()

    def log_interface(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.top, self.left, self.height, self.width)
        self.user = QLineEdit(self)
        self.user.setPlaceholderText('User Name')
        self.user.move(100, 150)
        self.pw = QLineEdit(self)
        self.pw.setPlaceholderText('Password')
        self.pw.move(100, 200)
        self.combo = QComboBox(self)
        for i in [dic1['user'] for dic1 in list_of_dic]:
            self.combo.addItem(i)
        self.combo.move(250, 150)
        self.combo.activated[str].connect(self.onchanged)
        btn = QPushButton('Click to login', self)
        btn.move(100, 300)
        btn.clicked.connect(self.login)
        btn1 = QPushButton('Click to Register!!!', self)
        btn1.move(200, 300)
        btn1.clicked.connect(self.regeister)
        self.show()

    def onchanged(self, text):
        self.user.setText(text)
        self.user.adjustSize()

    def regeister(self):
        pass

    def login(self):
        input_user = self.user.text()
        input_password = self.pw.text()
        if input_user in [dic['user'] for dic in list_of_dic]:
            if (input_user, input_password) in [(dic['user'], dic['password'])
                                                for dic in list_of_dic]:
                # print('login successfully')
                self.SW = VideoPlayerWindow(input_user)
                self.SW.show()
            else:
                # print('wrong password')
                QMessageBox.about(self, "Login Wrong!", "wrong password!")
        else:
            # print('no exist such a user')
            QMessageBox.about(self, "Login Wrong!", "no exist such a user!")
Esempio n. 7
0
class MyApp(QWidget):

    def __init__(self):
     super().__init__()
     self.text = ''
     self.initUI()

    def initUI(self):
#check box
     self.cb1 = QCheckBox('apple ', self)
     self.cb1.move(20, 20)
	
     self.cb2 = QCheckBox('banana ', self)
     self.cb2.move(20, 40)
    
     self.cb3 = QCheckBox('orange ', self)
     self.cb3.move(20, 60)

     self.cb1.stateChanged.connect(self.changeLedit1)
     self.cb2.stateChanged.connect(self.changeLedit2)
     self.cb3.stateChanged.connect(self.changeLedit3)
     self.setGeometry(300, 300, 300, 200)

#lineEdit
     self.qle = QLineEdit(self)
     self.qle.move(60, 100)
     self.show()
    
    def changeLedit1(self, state):
     if self.cb1.isChecked() == True:
      self.text += self.cb1.text()
     else :
      self.text = re.sub(self.cb1.text(),'', self.text)
     self.Ledit()

    def changeLedit2(self, state):
     if self.cb2.isChecked() == True:
      self.text += self.cb2.text()
     else : 
      self.text = re.sub(self.cb2.text(),'', self.text)
     self.Ledit()

    def changeLedit3(self, state):
     if self.cb3.isChecked() == True:
      self.text += self.cb3.text()
     else :
      self.text = re.sub(self.cb3.text(),'', self.text)
     self.Ledit()

    def Ledit(self) :
     self.qle.setText(self.text)
     self.qle.adjustSize()
Esempio n. 8
0
class PwdInitWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        sign_pwd = QLabel('비밀번호 입력', self)
        sign_pwd.move(20, 23)
        font_pwd = sign_pwd.font()
        font_pwd.setBold(True)
        font_pwd.setPointSize(20)
        setLabelStyle(sign_pwd)

        check_pwd = QLabel('비밀번호 확인', self)
        check_pwd.move(20, 53)
        font_check = check_pwd.font()
        font_check.setBold(True)
        font_check.setPointSize(20)
        setLabelStyle(check_pwd)

        self.pwd = QLineEdit(self)
        self.pwd.move(100, 180)
        self.pwd.setEchoMode(QLineEdit.Password)
        setEditStandard(self.pwd, 150, 20, '비밀번호')
        self.pwd.setFixedWidth(200)

        self.check_pwd = QLineEdit(self)
        self.check_pwd.setFixedWidth(200)
        self.check_pwd.setEchoMode(QLineEdit.Password)
        setEditStandard(self.check_pwd, 150, 50, '한번 더 입력')

        self.pwd_init_btn = QPushButton('비밀번호 변경', self)
        self.pwd_init_btn.move(120, 90)
        setButtonStyle(self.pwd_init_btn)

        self.go_back = QPushButton('돌아가기', self)
        self.go_back.move(240, 90)
        setButtonStyle(self.go_back)

    def onChanged(self, text):
        self.pwd.setText(text)
        self.pwd.adjustSize()
        self.check_pwd.setText(text)
        self.check_pwdt.adjustSize()

    def onPwdInitAlert(self):
        if (self.pwd.text() != self.check_pwd.text()):
            QMessageBox.about(self, 'DAIG', '비밀번호가 서로 일치하지 않습니다.')
        pass
Esempio n. 9
0
    def initUI(self):
        ledit = QLineEdit(self)
        ledit.setText("输入文字,选择并拖拽到按钮")
        ledit.adjustSize()
        ledit.setDragEnabled(True)
        ledit.move(30, 65)

        btn = Button("Button", self)
        btn.move(190, 65)

        # position
        self.setGeometry(300, 300, 350, 350)
        # window title
        self.setWindowTitle("simple drag and drop")
        # show window
        self.show()
Esempio n. 10
0
class RegisterWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.title = 'Register'
        self.top = 100
        self.left = 100
        self.width = 400
        self.height = 400
        self.register_interface()

    def register_interface(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.top, self.left, self.height, self.width)
        self.user = QLineEdit(self)
        self.user.setPlaceholderText('User Name')
        self.user.move(100, 150)
        self.pw = QLineEdit(self)
        self.pw.setPlaceholderText('Password')
        self.pw.move(100, 200)
        self.age = QLineEdit(self)
        self.age.setPlaceholderText('Age')
        self.age.move(100, 250)
        self.combo = QComboBox(self)
        for i in range(150):
            self.combo.addItem(str(i))
        self.combo.move(200, 250)
        self.combo.activated[str].connect(self.onchanged)
        btn = QPushButton('confirm to submit', self)
        btn.move(100, 300)
        btn.clicked.connect(self.register)
        self.show()

    def onchanged(self, text):
        self.age.setText(text)
        self.age.adjustSize()

    def register(self):
        input_user = self.user.text()
        input_password = self.pw.text()
        input_age = self.age.text()
        dic1 = dict()
        dic1['user'] = input_user
        dic1['password'] = input_password
        dic1['age'] = input_age
        list_of_dic.append(dic1)
        pickle.dump(list_of_dic,
                    open(user_info_pickle_path + "user_info.p", "wb"))
Esempio n. 11
0
class Voption(QWidget):
    def __init__(self):
        super().__init__()
        self.top = 100
        self.left = 100
        self.width = 1300
        self.height = 840
        self.Rozokar1()

    def Rozokar1(self):
        self.setWindowTitle("Remove")
        self.setGeometry(self.left, self.top, self.width, self.height)

        self.label = QLabel(self)
        self.label.setPixmap(QPixmap("new3.jpg"))

        self.label1 = QLabel(self)
        self.label1.setFont(QtGui.QFont("Arial", 15, QtGui.QFont.Black))
        self.label1.setStyleSheet("color: rgb(255,255,255)")
        self.label1.setText('Employee Id')
        self.label1.adjustSize()
        self.label1.move(50, 25)

        self.line1 = QLineEdit(self)
        self.line1.setFont(QFont('SansSerif', 14))
        self.line1.move(250, 25)
        self.line1.adjustSize()

        self.pushbutton1 = QPushButton("Back", self)
        self.pushbutton1.setFont(QFont('SansSerif', 14))
        self.pushbutton1.resize(self.pushbutton1.sizeHint())
        self.pushbutton1.move(180, 100)
        self.pushbutton1.clicked.connect(self.go_to_Weladmin)

        self.pushbutton2 = QPushButton("Remove", self)
        self.pushbutton2.setFont(QFont('SansSerif', 14))
        self.pushbutton2.resize(self.pushbutton1.sizeHint())
        self.pushbutton2.move(370, 100)
        self.pushbutton2.clicked.connect(self.go_to_Weladmin)

        self.show()

    def go_to_Weladmin(self):
        from Weladmin import Voption
        self.Voption = Voption()
        self.Voption.show()
        self.close()
Esempio n. 12
0
class EditBox(QWidget):
    """ Generate a simple box for editing

    """
    def __init__(self, initv, lbl, format, parent=None):
        """
        Parameters
        ----------
        initv : str
          Initial value
        lbl : str
        format : str
          Format for text
        """
        super(EditBox, self).__init__(parent)

        self.value = initv
        #
        label = QLabel(lbl)
        self.box = QLineEdit()
        # Format
        self.box.frmt = format
        self.box.setText(self.box.frmt.format(self.value))
        self.box.setMinimumWidth(90)
        # Connect
        self.box.textChanged[str].connect(self.setv)
        #self.connect(self.box,
        #    QtCore.SIGNAL('editingFinished ()'), self.setv)
        # Layout
        vbox = QVBoxLayout()
        vbox.addWidget(label)
        vbox.addWidget(self.box)
        self.setLayout(vbox)

    def setv(self, text):
        self.box.setText(text)
        self.box.adjustSize()
        self.value = str(self.box.text())

    def set_text(self,value):
        self.value = value
        self.box.setText(self.box.frmt.format(self.value))
Esempio n. 13
0
class AnsBox(QDialog):
    """Solicit an input answer from the User
    """
    def __init__(self, lbl, format=str, parent=None):
        """
        Parameters
        ----------
        lbl : str
        format : str
          Format for value
        """
        super(AnsBox, self).__init__(parent)

        self.format=format
        #
        label = QLabel(lbl)
        self.box = QLineEdit()
        self.box.setMinimumWidth(90)
        # Connect
        self.box.textChanged[str].connect(self.setv)
        self.box.editingFinished.connect(self.finish)
        # Layout
        vbox = QVBoxLayout()
        vbox.addWidget(label)
        vbox.addWidget(self.box)
        self.setLayout(vbox)

    def setv(self, text):
        self.box.setText(text)
        self.box.adjustSize()

    def finish(self):
        try:
            self.value = self.format(ustr(self.box.text()))
        except ValueError:
            print('Bad input value! Try again with right type')
        else:
            self.done(0)
Esempio n. 14
0
class FindPwdWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.email = ''

        sign_id = QLabel('ID', self)
        sign_id.move(20, 23)
        font_id = sign_id.font()
        font_id.setBold(True)
        font_id.setPointSize(20)
        setLabelStyle(sign_id)

        sign_email = QLabel('Email', self)
        sign_email.move(20, 53)
        font_email = sign_email.font()
        font_email.setBold(True)
        font_email.setPointSize(20)
        setLabelStyle(sign_email)

        alpha = QLabel('@', self)
        alpha.move(228, 53)

        self.id = QLineEdit(self)
        self.id.move(100, 180)
        setEditStandard(self.id, 75, 20, '아이디')
        self.id.setFixedWidth(150)

        self.email_front = QLineEdit(self)
        self.email_front.setFixedWidth(150)
        setEditStandard(self.email_front, 75, 50, '이메일')

        self.email_back = QLineEdit(self)
        self.email_back.setFixedWidth(150)
        setEditStandard(self.email_back, 245, 50, 'daig.co.kr')

        self.find_btn = QPushButton('비밀번호 찾기', self)
        self.find_btn.move(165, 90)
        setButtonStyle(self.find_btn)

        self.go_back = QPushButton('돌아가기', self)
        self.go_back.move(285, 90)
        setButtonStyle(self.go_back)

    def onChanged(self, text):
        self.id.setText(text)
        self.id.adjustSize()
        self.email_front.setText(text)
        self.email_front.adjustSize()
        self.email_back.setText(text)
        self.email_back.adjustSize()

    def onUserInfoAlert(self):
        self.email = self.email_front.text() + '@' + self.email_back.text()
Esempio n. 15
0
class BaseItemsPaging(QWidget):
    size = None
    position = None
    page_counter = None
    values = None
    main_layout = None
    h_students_layout = None
    widget_list = None
    items_per_page = 50

    def __init__(self, values):
        super().__init__()

        self.size = len(values)
        self.values = values
        self.position = 0

        self.main_layout = QVBoxLayout()
        self.page = QWidget()
        self.main_layout.addWidget(self.page)

        page_navigator = QHBoxLayout()

        self.page_counter = QLineEdit('1')
        self.page_counter.adjustSize()

        left_arrow = QPushButton()
        left_arrow.setIcon(QIcon('./images/left_arrow.png'))
        left_arrow.setStyleSheet("QPushButton { border: none; }")
        size = self.page_counter.sizeHint().height()
        left_arrow.setFixedSize(size, size)
        left_arrow.clicked.connect(self.go_left)

        right_arrow = QPushButton()
        right_arrow.setIcon(QIcon('./images/right_arrow.png'))
        right_arrow.setStyleSheet("QPushButton { border: none; }")
        right_arrow.setFixedSize(size, size)
        right_arrow.clicked.connect(self.go_right)

        page_navigator.addStretch()
        page_navigator.addWidget(left_arrow)
        page_navigator.addWidget(QLabel("Page:"))
        page_navigator.addWidget(self.page_counter)
        page_navigator.addWidget(
            QLabel("of {} pages".format(
                str((self.size - 1) // self.items_per_page + 1))))
        page_navigator.addWidget(right_arrow)
        page_navigator.addStretch()

        self.main_layout.addLayout(page_navigator)
        self.main_layout.addStretch()

        self.initialize_current()
        self.setLayout(self.main_layout)

    def initialize_current(self):
        pass

    def go_left(self):
        if int(self.page_counter.text()) - 1 <= 0:
            return
        if self.position != int(self.page_counter.text()) - 1:
            self.position = int(self.page_counter.text()) - 1
        else:
            self.position -= 1
            self.page_counter.setText(str(self.position + 1))
        self.initialize_current()

    def go_right(self):
        if int(self.page_counter.text()
               ) >= (self.size - 1) // self.items_per_page + 1:
            return
        if self.position != int(self.page_counter.text()) - 1:
            self.position = int(self.page_counter.text()) - 1
        else:
            self.position += 1
            self.page_counter.setText(str(self.position + 1))
        self.initialize_current()

    def search(self, text, widget_list):
        a = widget_list.get(text, None)
        keys = list(self.values.keys())
        if a is None:
            try:
                user = keys.index(text)
            except ValueError:
                return
            self.page_counter.setText(str((user // self.items_per_page + 1)))
            self.position = max(0, user // self.items_per_page)
            self.initialize_current()
            index = user % self.items_per_page
        else:
            index = self.h_students_layout.indexOf(a)
        first = self.h_students_layout.itemAt(0).widget()
        second = self.h_students_layout.itemAt(index).widget()
        if first == second:
            return
        first.setParent(None)
        second.setParent(None)
        self.h_students_layout.insertWidget(0, second)
        self.h_students_layout.insertWidget(index, first)
Esempio n. 16
0
class SignUpWidget(QWidget):
    # don't touch
    def __init__(self):
        super().__init__()
        self.initUI()

    # code
    def initUI(self):
        self.is_username_available = False
        self.check_email_authorized = False  # 이메일 인증 여부

        # 가입완료 버튼
        self.sign_submit = QPushButton('가입완료', self)
        self.sign_submit.move(255, 165)
        setButtonStyle(self.sign_submit)

        # 돌아가기 버튼
        self.go_back = QPushButton('돌아가기', self)
        self.go_back.move(375, 165)
        setButtonStyle(self.go_back)

        # 중복 아이디 확인 버튼
        self.code = ''
        self.dup_username = QPushButton('중복확인', self)
        self.dup_username.move(250, 22)
        setButtonStyle(self.dup_username)
        self.dup_username.setFixedWidth(50)
        self.dup_username.clicked.connect(self.check_username)

        # 이메일 인증 버튼
        self.email = ''
        self.send_email = QPushButton('인증', self)
        self.send_email.move(250, 107)
        setButtonStyle(self.send_email)
        self.send_email.setFixedWidth(50)
        self.send_email.clicked.connect(self.check_email)

        # 이메일 인증 버튼
        self.code = ''
        self.auth_code = QPushButton('확인', self)
        self.auth_code.move(170, 147)
        setButtonStyle(self.auth_code)
        self.auth_code.setFixedWidth(50)
        self.auth_code.clicked.connect(self.check_code)

        # 아이디, 비밀번호, 이메일 알리기
        sign_id = QLabel('ID', self)
        sign_id.move(20, 35)
        font_id = sign_id.font()
        font_id.setBold(True)
        font_id.setPointSize(20)
        setLabelStyle(sign_id)

        sign_pwd = QLabel('Password', self)
        sign_pwd.move(20, 75)
        font_pwd = sign_pwd.font()
        font_pwd.setBold(True)
        font_pwd.setPointSize(20)
        setLabelStyle(sign_pwd)

        sign_email = QLabel('Email', self)
        sign_email.move(20, 115)
        font_email = sign_email.font()
        font_email.setBold(True)
        font_email.setPointSize(20)
        setLabelStyle(sign_email)

        sign_code = QLabel('Code', self)
        sign_code.move(20, 155)
        font_code = sign_code.font()
        font_code.setBold(True)
        font_code.setPointSize(20)
        setLabelStyle(sign_code)

        # alpha = QLabel('@', self)
        # alpha.move(248, 113)

        # 아이디, 비밀번호, 이메일 작성
        self.id = QLineEdit(self)
        self.id.setFixedWidth(150)
        setEditStandard(self.id, 95, 30, '아이디')

        self.pwd = QLineEdit(self)
        self.pwd.setEchoMode(QLineEdit.Password)
        self.pwd.setFixedWidth(150)
        setEditStandard(self.pwd, 95, 70, '비밀번호')

        # self.email_front = QLineEdit(self)
        # self.email_front.setFixedWidth(150)
        # setEditStandard(self.email_front, 95, 110, '이메일')

        self.email = QLineEdit(self)
        self.email.setFixedWidth(150)
        setEditStandard(self.email, 95, 110, '이메일')

        self.code = QLineEdit(self)
        self.code.setFixedWidth(70)
        setEditStandard(self.code, 95, 150, '인증 코드')

    # 이메일 인증
    def check_email(self):
        self.check_email_authorized = False
        req_data = {'email': self.email.text()}
        res_data = verify_email(req_data)
        # if res_data['is_successful']:

        QMessageBox.about(self, 'DAIG', res_data["message"])

    def check_code(self):
        req_data = {'email': self.email.text(), 'code': self.code.text()}
        res_data = verify_code(req_data)
        if res_data['is_successful']:
            self.check_email_authorized = True
        QMessageBox.about(self, 'DAIG', res_data["message"])

    def check_username(self):
        self.is_username_available = False
        req_data = {
            'username': self.id.text(),
        }
        res_data = verify_username(req_data)
        if res_data['is_successful']:
            self.is_username_available = True
        QMessageBox.about(self, 'DAIG', res_data["message"])

    # onChange Handler
    def onChanged(self, text):
        self.id.setText(text)
        self.id.adjustSize()
        self.pwd.setText(text)
        self.pwd.adjustSize()
        self.email_front.setText(text)
        self.email_front.adjustSize()
        # self.email_back.setText(text)
        # self.email_back.adjustSize()

    def onClickSignUp(self):
        if (self.is_username_available == False):
            QMessageBox.about(self, 'DAIG', 'ID 중복확인을 해주세요.')
            return

        if (self.check_email_authorized == False):
            QMessageBox.about(self, 'DAIG', '이메일 인증을 해주세요.')
            return
        sender_data = {
            "username": self.id.text(),
            "password": self.pwd.text(),
            "email": self.email.text()
        }
        res = sign_up_req(sender_data)
        if (res["is_successful"] == True):
            QMessageBox.about(self, 'DAIG', res["message"])
            return True
        else:
            QMessageBox.about(self, 'DAIG', res["message"])
            return False
class WindowClass(QWidget):  #创建一个windowclass类
    def __init__(self, parent=None):  #初始化
        super(WindowClass, self).__init__(parent)
        global img_cv
        win_layout = QHBoxLayout()  #整体布局
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.data_receive)

        self.resize(250, 300)  #窗口大小
        self.setWindowTitle("Openmv image analyse")  #窗口标题
        #label 对象
        self.LabLAB1 = QLabel()
        self.LabLAB2 = QLabel()
        self.LabLAB3 = QLabel()
        #lab 范围 label 的内容
        self.LabLAB1.setText("L:" + str(Lab_list[1]) + "-" + str(Lab_list[0]) +
                             "  X:" + str(position_list[0]))
        self.LabLAB2.setText("A:" + str(Lab_list[3]) + "-" + str(Lab_list[2]) +
                             "  Y:" + str(position_list[1]))
        self.LabLAB3.setText("B:" + str(Lab_list[5]) + "-" + str(Lab_list[4]) +
                             "  Width:" + str(position_list[2]) + "  Height:" +
                             str(position_list[3]))
        #字体设置
        font = QtGui.QFont()
        font.setPointSize(12)

        self.LabLAB1.setFont(font)
        self.LabLAB2.setFont(font)
        self.LabLAB3.setFont(font)
        #lab_set label lab值标签的内容
        self.labLAB_set1 = QLabel()
        self.labLAB_set2 = QLabel()
        self.labLAB_set3 = QLabel()

        self.labLAB_set1.setText("L:")
        self.labLAB_set2.setText("A:")
        self.labLAB_set3.setText("B:")

        font.setPointSize(12)
        self.labLAB_set1.setFont(font)
        self.labLAB_set2.setFont(font)
        self.labLAB_set3.setFont(font)

        #lab值设定编辑框
        self.L_set_edit = QLineEdit()
        self.A_set_edit = QLineEdit()
        self.B_set_edit = QLineEdit()

        self.L_set_edit.setText(str(Lab_list[1]) + "-" + str(Lab_list[0]))
        self.A_set_edit.setText(str(Lab_list[3]) + "-" + str(Lab_list[2]))
        self.B_set_edit.setText(str(Lab_list[5]) + "-" + str(Lab_list[4]))
        #    self.L_set_edit.setMaximumWidth(QtGui.QFontMetrics(QtGui.QFont(self.L_set_edit.text())).width(self.L_set_edit.text()))

        self.L_set_edit.adjustSize()
        self.A_set_edit.adjustSize()
        self.B_set_edit.adjustSize()

        #xy_set lable
        self.x_set_lab = QLabel()
        self.y_set_lab = QLabel()
        #width height lable
        self.width_set_lab = QLabel()
        self.height_set_lab = QLabel()
        #xy_set label的内容
        self.x_set_lab.setText("X:")
        self.y_set_lab.setText("Y:")
        self.x_set_lab.setFont(font)
        self.y_set_lab.setFont(font)
        #height,width label的内容
        self.height_set_lab.setText("Height:")
        self.width_set_lab.setText("Width:")

        self.X_set_edit = QLineEdit()
        self.Y_set_edit = QLineEdit()

        self.X_set_edit.setText(str(position_list[0]))
        self.Y_set_edit.setText(str(position_list[1]))
        #width,height edit

        self.width_set_edit = QLineEdit()
        self.height_set_edit = QLineEdit()

        self.width_set_edit.setText(str(position_list[2]))
        self.height_set_edit.setText(str(position_list[3]))
        ##################################################
        #盘符下拉框 ,盘符标签

        self.device_lab = QLabel()
        self.device_lab.setText("请选择openmv的盘符:")
        self.device_lab.setFont(font)
        self.device_lab.setScaledContents(True)
        self.device_combobox = QComboBox()

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

        #com端口下拉框 , com标签,串口信息标签,检测按钮
        self.s1_lable_com = QLabel()
        self.s1_box_1 = QComboBox()
        self.s1_lable_com.setText("COM:")
        self.s1_lable_com.setScaledContents(True)
        #  self.s1_lable_com.setFixedWidth(28)   #设定label宽度
        self.com_state_lable = QLabel()
        self.com_state_lable.setText("当前串口为:无")
        self.com_state_lable.setFont(font)

        self.s1_lable_com.setFixedWidth(
            QtGui.QFontMetrics(QtGui.QFont(self.s1_lable_com.text())).width(
                self.s1_lable_com.text()))  #设定label宽度

        self.s1_lable_com.setFont(font)
        self.s1_comcheck_btn1 = QPushButton("检测串口")
        self.s1_comopen_btn2 = QPushButton("打开串口")
        self.s1_comclose_btn3 = QPushButton("关闭串口")
        self.s1_savedata_btn4 = QPushButton("保存ROI和LAB阈值到openmv")
        self.s1_comclear_btn5 = QPushButton("清空ROI和LAB数据")
        self.s1_comclose_btn3.setEnabled(False)
        self.s1_comdata_label = QLabel("串口接收到的数据:")
        self.s1_comdata_receive = QLineEdit()

        self.btn_1 = QPushButton("连接openmv")
        self.btn_2 = QPushButton("截取图像")
        self.btn_3 = QPushButton("显示RGB直方图")
        '''
        按钮美化
        self.btn_3.setStyleSheet("QPushButton{color:black}"
                                  "QPushButton:hover{color:red}"
                                  "QPushButton{background-color:rgb(78,255,255)}"
                                  "QPushButton{border:2px}"
                                  "QPushButton{border-radius:10px}"
                                  "QPushButton{padding:2px 4px}")
        '''
        ########左控件布局########
        lwg = QWidget()  #左控件总容器

        lgroupBox1 = QGroupBox("截取的图像")  #左控件控件框1,用法等同于QWidget
        lgroupBox2 = QGroupBox("选定的ROI图像")  #左控件控件框2
        hlayout1 = QHBoxLayout()
        hlayout2 = QHBoxLayout()

        self.shotshow = cvLabel(self)
        self.roishow = cvLabel(self)
        self.shotshow.setMaximumSize(300, 400)
        self.roishow.setMaximumSize(300, 400)

        self.shotshow.setCursor(Qt.CrossCursor)

        hlayout1.addWidget(self.shotshow)
        hlayout2.addWidget(self.roishow)

        lgroupBox1.setLayout(hlayout1)
        lgroupBox2.setLayout(hlayout2)

        lvlayout = QVBoxLayout()  #左控件总布局
        lvlayout.addWidget(lgroupBox1)
        lvlayout.addWidget(lgroupBox2)

        lwg.setLayout(lvlayout)

        win_layout.addWidget(lwg)

        #########中控件布局#########
        cwg = QWidget()  #中间的控件
        vlayout = QVBoxLayout()
        vlayout.addWidget(self.LabLAB1)
        vlayout.addWidget(self.LabLAB2)
        vlayout.addWidget(self.LabLAB3)
        vlayout.addWidget(self.btn_1)
        vlayout.addWidget(self.btn_2)
        vlayout.addWidget(self.btn_3)
        cwg.setLayout(vlayout)

        win_layout.addWidget(cwg)

        #########右控件布局########
        rwg = QWidget()  #右边的控件

        rwg1 = QWidget(
        )  #定义六个控件作为次级容器, 普通控件->次级布局->次级控件容器(rwg/rwg_com)->右控件布局->右控件容器
        rwg2 = QWidget()
        rwg3 = QWidget()
        rwg4 = QWidget()
        rwg5 = QWidget()
        rwg6 = QWidget()
        rwg_com1 = QWidget()
        rwg_com2 = QWidget()
        rwg_com3 = QWidget()
        rwg_com4 = QWidget()

        #串口发送模块的端口选择部分GUI
        rwg_com_layout1 = QHBoxLayout()  #横向布局
        rwg_com_layout1.addWidget(self.s1_lable_com)

        rwg_com_layout1.addWidget(self.s1_box_1)
        rwg_com_layout1.addWidget(self.s1_comcheck_btn1)

        rwg_com_layout2 = QHBoxLayout()  #横向布局
        rwg_com_layout2.addWidget(self.s1_comopen_btn2)
        rwg_com_layout2.addWidget(self.s1_comclose_btn3)

        rwg_com_layout3 = QHBoxLayout()  #横向布局
        rwg_com_layout3.addWidget(self.s1_savedata_btn4)
        rwg_com_layout3.addWidget(self.s1_comclear_btn5)

        rwg_com_layout4 = QHBoxLayout()  #横向布局
        rwg_com_layout4.addWidget(self.s1_comdata_label)
        rwg_com_layout4.addWidget(self.s1_comdata_receive)

        rwg1_hlayout = QHBoxLayout()  #横向布局1

        rwg1_hlayout.addWidget(self.s1_box_1)
        rwg1_hlayout.addWidget(self.labLAB_set1)  #添加控件labLAB_set1
        rwg1_hlayout.addWidget(self.L_set_edit)
        rwg1_hlayout.setSizeConstraint(5)

        rwg2_hlayout = QHBoxLayout()  #横向布局2
        rwg2_hlayout.addWidget(self.labLAB_set2)  #添加控件labLAB_set2
        rwg2_hlayout.addWidget(self.A_set_edit)  #添加控件

        rwg3_hlayout = QHBoxLayout()  #横向布局3
        rwg3_hlayout.addWidget(self.labLAB_set3)  #添加控件
        rwg3_hlayout.addWidget(self.B_set_edit)  #添加控件

        rwg4_hlayout = QHBoxLayout()  #横向布局4
        rwg4_hlayout.addWidget(self.x_set_lab)
        rwg4_hlayout.addWidget(self.X_set_edit)
        rwg4_hlayout.addWidget(self.y_set_lab)
        rwg4_hlayout.addWidget(self.Y_set_edit)

        rwg5_hlayout = QHBoxLayout()  #横向布局5
        rwg5_hlayout.addWidget(self.width_set_lab)
        rwg5_hlayout.addWidget(self.width_set_edit)
        rwg5_hlayout.addWidget(self.height_set_lab)
        rwg5_hlayout.addWidget(self.height_set_edit)

        rwg6_hlayout = QHBoxLayout()  #横向布局6    盘符选择
        rwg6_hlayout.addWidget(self.device_lab)
        rwg6_hlayout.addWidget(self.device_combobox)

        rwg1.setLayout(rwg1_hlayout)  #把布局添加到控件
        rwg2.setLayout(rwg2_hlayout)  #把布局添加到控件
        rwg3.setLayout(rwg3_hlayout)
        rwg4.setLayout(rwg4_hlayout)
        rwg5.setLayout(rwg5_hlayout)
        rwg6.setLayout(rwg6_hlayout)

        rwg_com1.setLayout(rwg_com_layout1)
        rwg_com2.setLayout(rwg_com_layout2)
        rwg_com3.setLayout(rwg_com_layout3)
        rwg_com4.setLayout(rwg_com_layout4)

        rwg_layout_all = QVBoxLayout()  #设定一个窗体右边的纵向布局。

        rwg_layout_all.addWidget(rwg_com1)
        rwg_layout_all.addWidget(self.com_state_lable)
        rwg_layout_all.addWidget(rwg_com2)
        rwg_layout_all.addWidget(rwg_com4)
        #  rwg_layout_all.addWidget(self.s1_comdata_receive)
        rwg_layout_all.addWidget(rwg1)  #添加控件
        rwg_layout_all.addWidget(rwg2)  #添加控件
        rwg_layout_all.addWidget(rwg3)  #添加控件
        rwg_layout_all.addWidget(rwg4)  #添加控件
        rwg_layout_all.addWidget(rwg5)
        rwg_layout_all.addWidget(rwg6)
        rwg_layout_all.addWidget(rwg_com3)

        rwg.setLayout(rwg_layout_all)  #设定控件

        win_layout.addWidget(rwg)

        self.setLayout(win_layout)

        self.ser = serial.Serial()
        self.port_check()
        self.port_imf()
        self.get_disk_device()

        ####按钮信号槽#####
        self.btn_1.setCheckable(False)  #设置已经被点击
        self.btn_1.clicked.connect(self.btn1State)
        #self.btn_1.clicked.connect(lambda :self.wichBtn(self.btn_1))

        self.btn_2.setEnabled(False)  #设置不可用状态
        self.btn_2.clicked.connect(self.btn2State)
        # self.btn_2.clicked.connect(lambda :self.wichBtn(self.btn_2))

        self.btn_3.setEnabled(False)
        self.btn_3.clicked.connect(self.btn3State)
        #   self.btn_3.clicked.connect(self.check_frame_buffer_msg)
        self.s1_comcheck_btn1.clicked.connect(self.port_check)
        self.s1_comopen_btn2.clicked.connect(self.port_open)
        self.s1_comclose_btn3.clicked.connect(self.port_close)
        self.s1_box_1.currentTextChanged.connect(self.port_imf)
        self.s1_savedata_btn4.clicked.connect(self.save_lab_roi_data)
        self.s1_comclear_btn5.clicked.connect(self.clear_roi_lab)

    def check_frame_buffer_msg(self):
        while win32gui.FindWindow('pygame',
                                  'Frame Buffer') != 0:  #搜索图像传输框,如果存在返回0,发出警告
            check_message = QMessageBox.information(
                self, "警告", "请先关闭图像传输框(Frame Buffer)!", QMessageBox.Yes)

    def btn1State(self):
        if self.btn_1.isEnabled():
            #   print("Btn_1被点击")
            self.btn_2.setEnabled(True)

            win32api.ShellExecute(0, 'open', 'transfer_jpg_streaming.exe', 'a',
                                  '', 1)  # 前台打开

    def btn2State(self):
        global img
        if self.btn_2.isEnabled():
            self.btn_3.setEnabled(True)
            #   print("Btn_2被点击")
            get_window_jpg()
            cv2.resizeWindow('image', 640, 480)
            #   get_image_roi(img_cv)
            lab_data()

    def btn3State(self):
        if self.btn_3.isEnabled():
            #  print("Btn_3被点击")
            RGB_hist_show()

    def port_check(self):
        # 检测所有存在的串口,将信息存储在字典中
        self.Com_Dict = {}
        port_list = list(serial.tools.list_ports.comports())
        self.s1_box_1.clear()
        for port in port_list:
            self.Com_Dict["%s" % port[0]] = "%s" % port[1]
            self.s1_box_1.addItem(port[0])

        if len(self.Com_Dict) == 0:
            self.com_state_lable.setText("当前串口为:无串口")
        self.port_imf()

    # 串口信息
    def port_imf(self):
        # 显示选定的串口的详细信息
        imf_s = self.s1_box_1.currentText()

        if imf_s != "":
            self.com_state_lable.setText(
                "当前串口为:" + str(self.Com_Dict[self.s1_box_1.currentText()]))

    def port_open(self):
        if self.s1_comopen_btn2.isEnabled():
            #   print("open success!")
            self.ser.port = self.s1_box_1.currentText()
            self.ser.baudrate = 115200
            self.ser.bytesize = 8
            self.ser.stopbits = 1
            self.ser.parity = "N"
            self.port_imf()

            try:
                self.ser.open()
            except:
                QMessageBox.critical(self, "Port Error", "此串口不能被打开!")
                return None
                # 打开串口接收定时器,周期为2ms
            self.timer.start(2)
            #   print("set timer successful")

            if self.ser.isOpen():
                self.s1_comopen_btn2.setEnabled(False)
                self.s1_comclose_btn3.setEnabled(True)
                self.s1_savedata_btn4.setEnabled(True)
                self.com_state_lable.setText("串口状态(已开启)")

    # 关闭串口
    def port_close(self):
        try:
            self.ser.close()
        except:
            pass
        self.s1_comopen_btn2.setEnabled(True)
        self.s1_comclose_btn3.setEnabled(False)
        # 接收数据和发送数据数目置零
        '''
        self.data_num_received = 0
        self.lineEdit.setText(str(self.data_num_received))
        self.data_num_sended = 0
        self.lineEdit_2.setText(str(self.data_num_sended))
        '''
        self.com_state_lable.setText("串口状态(已关闭)")

    # 接收数据
    def data_receive(self):
        try:
            num = self.ser.inWaiting()
        except:
            self.port_close()
            return None
        if num > 0:
            data = self.ser.read(num)
            num = len(data)
            # hex显示
            if False:
                #self.hex_receive.checkState():
                out_s = ''
                for i in range(0, len(data)):
                    out_s = out_s + '{:02X}'.format(data[i]) + ' '
                self.s1_comdata_receive.setText(out_s)
            #  print(out_s)
            else:
                # 串口接收到的字符串为b'123',要转化成unicode字符串才能输出到窗口中去
                self.s1_comdata_receive.setText(data.decode('utf-8'))
            #  print(data.decode('utf-8'))
            # 统计接收字符的数量

    #     self.data_num_received += num
    #     self.lineEdit.setText(str(self.data_num_received))

    # 获取到text光标
    # textCursor = self.s2__receive_text.textCursor()
    # 滚动到底部
    # textCursor.movePosition(textCursor.End)
    # 设置光标到text中去
    # self.s2__receive_text.setTextCursor(textCursor)
        else:
            pass

    def get_disk_device(self):  #获取计算机盘符,添加到下拉框中
        disk = str(psutil.disk_partitions())
        disk_device = r'device'
        for i in re.finditer('device', disk):
            #print(i.span())
            start = i.span()[1] + 2  #盘符字符串起始位置
            end = i.span()[1] + 4  #盘符字符串终止位置
            #    print(disk[start:end])
            self.device_combobox.addItem(disk[start:end])

    def save_lab_roi_data(self):
        #######将lab编辑框中的内容读取至lab_list#######
        global Lab_list, position_list
        lab_s = str(self.L_set_edit.text())
        where = lab_s.find('-')
        # print(lab_s[0:where])
        Lab_list[0] = float(lab_s[0:where])
        where = where + 1
        Lab_list[1] = float(lab_s[where:len(lab_s)])

        lab_s = str(self.A_set_edit.text())
        if lab_s[0] == '-':
            lab_s = lab_s[1:len(lab_s)]
            where = lab_s.find('-')
            Lab_list[2] = -1 * float(lab_s[0:where])
            if lab_s[where + 1] == '-':
                where = where + 2
                Lab_list[3] = -1 * float(lab_s[where:len(lab_s)])
            else:
                where = where + 1
                Lab_list[3] = float(lab_s[where:len(lab_s)])
        else:
            where = lab_s.find('-')
            Lab_list[2] = float(lab_s[0:where])
            #  print(lab_s[0:where])
            where = where + 1
            Lab_list[3] = float(lab_s[where:len(lab_s)])
        #    print(lab_s[where:len(lab_s)])

        lab_s = str(self.B_set_edit.text())
        if lab_s[0] == '-':
            lab_s = lab_s[1:len(lab_s)]
            where = lab_s.find('-')
            Lab_list[4] = -1 * float(lab_s[0:where])
            if lab_s[where + 1] == '-':
                where = where + 2
                Lab_list[5] = -1 * float(lab_s[where:len(lab_s)])
            else:
                where = where + 1
                Lab_list[5] = float(lab_s[where:len(lab_s)])
        else:
            where = lab_s.find('-')
            Lab_list[4] = float(lab_s[0:where])
            #  print(lab_s[0:where])
            where = where + 1
            Lab_list[5] = float(lab_s[where:len(lab_s)])
        #   print(lab_s[where:len(lab_s)])

        #######将roi编辑框中的内容读取至roi_list#######

        roi_s = str(self.X_set_edit.text())
        position_list[0] = int(roi_s)

        roi_s = str(self.Y_set_edit.text())
        position_list[1] = int(roi_s)

        roi_s = str(self.width_set_edit.text())
        position_list[2] = int(roi_s)

        roi_s = str(self.height_set_edit.text())
        position_list[3] = int(roi_s[0:where])

        with open(str(self.device_combobox.currentText()) + '\data.txt',
                  'w') as data_txt:
            data = str(Lab_list[0]) + "," + str(Lab_list[1]) + "," + str(
                Lab_list[2]) + "," + str(Lab_list[3]) + "," + str(
                    Lab_list[4]) + "," + str(Lab_list[5])
            data_txt.writelines(data)
            data = str(position_list[0]) + "," + str(
                position_list[1]) + "," + str(position_list[2]) + "," + str(
                    position_list[3])
            data_txt.writelines('\n')
            data_txt.writelines(data)

    def clear_roi_lab(self):
        global Lab_list, position_list
        for i in range(6):
            Lab_list[i] = 0
        for i in range(4):
            position_list[i] = 0
        #重置xylab标签和xylab编辑框
        self.LabLAB1.setText("L:" + str(Lab_list[1]) + "-" + str(Lab_list[0]) +
                             "  X:" + str(position_list[0]))
        self.LabLAB2.setText("A:" + str(Lab_list[3]) + "-" + str(Lab_list[2]) +
                             "  Y:" + str(position_list[1]))
        self.LabLAB3.setText("B:" + str(Lab_list[5]) + "-" + str(Lab_list[4]) +
                             "  Width:" + str(position_list[2]) + "  Height:" +
                             str(position_list[3]))
        self.L_set_edit.setText(str(Lab_list[1]) + "-" + str(Lab_list[0]))
        self.A_set_edit.setText(str(Lab_list[3]) + "-" + str(Lab_list[2]))
        self.B_set_edit.setText(str(Lab_list[5]) + "-" + str(Lab_list[4]))
        self.X_set_edit.setText(str(position_list[0]))
        self.Y_set_edit.setText(str(position_list[1]))
        self.height_set_edit.setText(str(position_list[3]))
        self.width_set_edit.setText(str(position_list[2]))
Esempio n. 18
0
class XAbsSysGui(QDialog):
    """ GUI to replace XIDL x_velplot (and more)
    """
    def __init__(self, ispec, abs_sys, parent=None, llist=None, norm=True,
                 vmnx=[-300., 300.]*u.km/u.s, outfil=None):
        """
        spec : Filename or Spectrum1D
        abs_sys : AbsSystem
          Absorption system class
        Norm : bool, optional
          Normalized spectrum?
        """
        from linetools.guis import spec_widgets as ltgs
        super(XAbsSysGui, self).__init__(parent)

        # Initialize
        self.abs_sys = abs_sys
        self.z = self.abs_sys.zabs
        abs_lines = abs_sys.list_of_abslines()
        self.vmnx = vmnx
        if outfil is None:
            self.outfil = 'tmp_abskin.json'
            warnings.warn("Outfil not specified.  Using {:s} as the default".format(self.outfil))
        else:
            self.outfil = outfil
        self.norm = norm

        # Grab the pieces and tie together
        newfont = QtGui.QFont("Times", 10, QtGui.QFont.Bold)
        sys_label = QLabel('Name: \n {:s}'.format(abs_sys.name))
        sys_label.setFont(newfont)
        self.vplt_widg = ltgs.VelPlotWidget(ispec, self.z, abs_lines=abs_lines, llist=llist,
                                            vmnx=self.vmnx, norm=self.norm)
        self.pltline_widg = ltgl.PlotLinesWidget(init_llist=self.vplt_widg.llist,
                                                 init_z=self.z, edit_z=False)
        #self.pltline_widg.spec_widg = self.vplt_widg

        self.slines = ltgl.SelectedLinesWidget(self.vplt_widg.llist[self.vplt_widg.llist['List']],
                                               init_select=self.vplt_widg.llist['show_line'],
                                               plot_widget=self.vplt_widg)

        # Connections
        self.pltline_widg.llist_widget.currentItemChanged.connect(self.on_llist_change)
        #self.connect(self.pltline_widg.zbox, QtCore.SIGNAL('editingFinished ()'), self.setz)
        self.vplt_widg.canvas.mpl_connect('key_press_event', self.on_key)

        # Outfil
        wbtn = QPushButton(self)
        wbtn.setText('Write')
        wbtn.setAutoDefault(False)
        wbtn.clicked.connect(self.write_out)
        self.out_box = QLineEdit()
        self.out_box.setText(self.outfil)
        self.out_box.textChanged[str].connect(self.set_outfil)
        #self.connect(self.out_box, QtCore.SIGNAL('editingFinished ()'), self.set_outfil)

        #QtCore.pyqtRemoveInputHook()
        #pdb.set_trace()
        #QtCore.pyqtRestoreInputHook()

        # Quit
        buttons = QWidget()
        wqbtn = QPushButton(self)
        wqbtn.setText('Write+Quit')
        wqbtn.setAutoDefault(False)
        wqbtn.clicked.connect(self.write_quit)
        qbtn = QPushButton(self)
        qbtn.setText('Quit')
        qbtn.setAutoDefault(False)
        qbtn.clicked.connect(self.quit)

        # Sizes
        lines_widg = QWidget()
        lines_widg.setMaximumWidth(300)
        lines_widg.setMinimumWidth(200)

        # Layout
        vbox = QVBoxLayout()
        vbox.addWidget(sys_label)
        vbox.addWidget(self.pltline_widg)
        vbox.addWidget(self.slines)
        vbox.addWidget(wbtn)
        vbox.addWidget(self.out_box)
        # Write/Quit buttons
        hbox1 = QHBoxLayout()
        hbox1.addWidget(wqbtn)
        hbox1.addWidget(qbtn)
        buttons.setLayout(hbox1)
        #
        vbox.addWidget(buttons)
        lines_widg.setLayout(vbox)

        hbox = QHBoxLayout()
        hbox.addWidget(self.vplt_widg)
        hbox.addWidget(lines_widg)

        self.setLayout(hbox)
        # Initial draw
        self.vplt_widg.on_draw()

    # Overload, as needed
    def on_key(self, event):
        pass

    # Change list of lines to choose from
    def on_llist_change(self):
        llist = self.pltline_widg.llist
        all_lines = list( llist[llist['List']]._data['wrest'] )
        # Set selected
        wrest = [line.wrest for line in self.vplt_widg.abs_lines]
        select = []
        for iwrest in wrest:
            try:
                select.append(all_lines.index(iwrest))
            except ValueError:
                pass
        select.sort()
        # GUIs
        self.vplt_widg.llist['List'] = llist['List']
        self.vplt_widg.llist['show_line'] = select
        self.vplt_widg.idx_line = 0
        self.slines.selected = select
        self.slines.on_list_change(llist[llist['List']])

    # Write
    def set_outfil(self, text):
        self.out_box.setText(text)
        self.out_box.adjustSize()
        self.outfil = str(self.out_box.text())
        print('AbsKin: Will write to {:s}'.format(self.outfil))

    '''
    # Set z from pltline_widg
    def setz(self):
        self.vplt_widg.z = self.pltline_widg.llist['z']
        self.z = self.pltline_widg.llist['z']
        self.vplt_widg.on_draw()
    '''

    def set_new_comps(self):
        """ Generate new components and fill into abs_sys
        Ignores velocity limits when building
        """
        # Add spectrum filename, coord
        abs_lines = self.vplt_widg.abs_lines
        for line in abs_lines:
            line.analy['datafile'] = self.vplt_widg.spec_fil
            line.attrib['coord'] = self.abs_sys.coord
        # Components
        comps = ltiu.build_components_from_abslines(abs_lines, chk_vel=False)
        self.abs_sys._components = comps
        # Return
        return

    # Write
    @pyqtSlot()
    def write_out(self):
        # Update components and spectrum filename
        self.set_new_comps()
        # Dict
        adict = self.abs_sys.to_dict()

        #QtCore.pyqtRemoveInputHook()
        #xdb.set_trace()
        #QtCore.pyqtRestoreInputHook()
        print("Wrote abs_sys to {:s}".format(self.outfil))
        with io.open(self.outfil, 'w', encoding='utf-8') as f:
            f.write(json.dumps(adict, sort_keys=True, indent=4,
                                       separators=(',', ': ')))

    # Write + Quit
    @pyqtSlot()
    def write_quit(self):
        self.write_out()
        self.flg_quit = 1
        self.done(1)

    # Write + Quit
    @pyqtSlot()
    def quit(self):
        self.flg_quit = 0
        self.done(1)
Esempio n. 19
0
class PatternDialog(QDialog):
    """QDialog derived class which is used to configure display of
    a pattern file.
    """

    def __init__(self, filename: str = None, parent=None, control=None):
        """Constructor for PatternDialog class.
        filename is the path to the file containing data of
            antenna pattern
        parent is the EarthPlot instance which will display
            the antenna pattern
        control is the antenna pattern controler instance
        """
        utils.trace()
        # Parent constructor
        super().__init__()

        # abort the pattern loading ?
        self.abort = True

        # configure widget
        self.filename = filename
        self.earth_plot = parent
        self._control = control
        self._patternctlr = None
        self._plot = None
        self._item = None
        if control is not None:
            self._patternctlr = control._pattern
            self._plot = control._plot
            self._item = control._pattern_sub_menu

        # Add Title to the widget
        self.setWindowTitle('Load pattern')
        self.setMinimumSize(100, 100)

        # Everything in a vertical Layout
        vbox = QVBoxLayout(self)

        # Add file name
        self.filename_label = QLabel('File', parent=self)
        self.filename_field = QLineEdit('Dummy_file.txt', parent=self)
        self.filename_field.setEnabled(False)
        self.filename_field.adjustSize()
        hbox_filename = QHBoxLayout(None)
        hbox_filename.addWidget(self.filename_label)
        hbox_filename.addWidget(self.filename_field)
        vbox.addLayout(hbox_filename)

        # Add Title field
        self.title_label = QLabel('Title', parent=self)
        self.title_field = QLineEdit('Default Title', parent=self)
        hbox_title = QHBoxLayout(None)
        hbox_title.addWidget(self.title_label)
        hbox_title.addWidget(self.title_field)
        vbox.addLayout(hbox_title)

        # Add longitude/latitude/altitude fields
        self.lon_label = QLabel('Lon.', parent=self)
        self.lon_field = QLineEdit('0.0', parent=self)
        self.lat_label = QLabel('Lat.', parent=self)
        self.lat_field = QLineEdit('0.0', parent=self)
        self.alt_label = QLabel('Alt.', parent=self)
        self.alt_field = QLineEdit('0.0', parent=self)
        self.yaw_label = QLabel('Yaw', parent=self)
        self.yaw_field = QLineEdit('0.0', parent=self)
        hbox_sat_position = QHBoxLayout(None)
        hbox_sat_position.addWidget(self.lon_label)
        hbox_sat_position.addWidget(self.lon_field)
        hbox_sat_position.addStretch(1)
        hbox_sat_position.addWidget(self.lat_label)
        hbox_sat_position.addWidget(self.lat_field)
        hbox_sat_position.addStretch(1)
        hbox_sat_position.addWidget(self.alt_label)
        hbox_sat_position.addWidget(self.alt_field)
        hbox_sat_position.addStretch(1)
        hbox_sat_position.addWidget(self.yaw_label)
        hbox_sat_position.addWidget(self.yaw_field)
        hbox_sat_position.addStretch(1)
        vbox.addLayout(hbox_sat_position)

        # Add isolevel
        self.isolevel_label = QLabel('Isolevels', parent=self)
        self.isolevel_field = QLineEdit(self.get_isolevel(), parent=self)
        self.cf_label = QLabel('Conv. Factor', parent=self)
        self.cf_field = QLineEdit('0.0', parent=self)
        hbox_isolevel = QHBoxLayout(None)
        hbox_isolevel.addWidget(self.isolevel_label)
        hbox_isolevel.addWidget(self.isolevel_field)
        hbox_isolevel.addWidget(self.cf_label)
        hbox_isolevel.addWidget(self.cf_field)
        vbox.addLayout(hbox_isolevel)

        # Add special combo box for multigrd
        if 'law'in self._patternctlr.configure().keys():
            self.law_id_lbl = QLabel('Excitation law', parent=self)
            self.law_id_cmb = QComboBox(self)
            self.law_id_cmb.addItems(self._patternctlr.configure()['law'])
            self.law_id_cmb.setCurrentText(
                self._patternctlr.configure()['applied_law'])
            self.law_id_cmb.currentTextChanged.connect(self.cmb_law_changed)
            hbox_law = QHBoxLayout(None)
            hbox_law.addWidget(self.law_id_lbl)
            hbox_law.addWidget(self.law_id_cmb)
            vbox.addLayout(hbox_law)

        # Add checkboxes
        self.chk_revert_x = QCheckBox('Revert X axis', parent=self)
        self.chk_revert_y = QCheckBox('Revert Y axis', parent=self)
        self.chk_rotate = QCheckBox('Rotate 180deg', parent=self)
        hbox_revert = QHBoxLayout(None)
        hbox_revert.addWidget(self.chk_revert_x)
        hbox_revert.addWidget(self.chk_revert_y)
        hbox_revert.addWidget(self.chk_rotate)
        vbox.addLayout(hbox_revert)

        # options grid layout
        self.chkxpol = QCheckBox('Use crosspol data', parent=self)
        self.chkxpol.stateChanged.connect(self.refresh_isolevel)
        self.chkslope = QCheckBox('Display Slope', parent=self)
        self.chkslope.stateChanged.connect(self.chk_display_slope_changed)
        self.chksurf = QCheckBox('Color surface', parent=self)
        optionbox = QGridLayout(None)
        optionbox.addWidget(self.chkxpol, 1, 1)
        optionbox.addWidget(self.chkslope, 1, 2)
        optionbox.addWidget(self.chksurf, 1, 3)
        vbox.addLayout(optionbox)

        # add offset sub form
        self.chk_offset = QCheckBox('Offset', parent=self)
        self.offset_button = QPushButton('Lon/Lat', parent=self)
        self.offset_button.setCheckable(True)
        self.offset_button.toggle()
        self.az_offset_label = QLabel('Az.', parent=self)
        self.az_offset_field = QLineEdit('0.0', parent=self)
        self.el_offset_label = QLabel('El.', parent=self)
        self.el_offset_field = QLineEdit('0.0', parent=self)
        self.az_offset_label.setFixedWidth(40)
        self.el_offset_label.setFixedWidth(40)
        self.az_offset_label.setAlignment(QtCore.Qt.AlignRight
                                          | QtCore.Qt.AlignVCenter)
        self.el_offset_label.setAlignment(QtCore.Qt.AlignRight
                                          | QtCore.Qt.AlignVCenter)
        self.az_offset_field.setFixedWidth(80)
        self.el_offset_field.setFixedWidth(80)
        self.az_offset_field.setAlignment(QtCore.Qt.AlignRight
                                          | QtCore.Qt.AlignVCenter)
        self.el_offset_field.setAlignment(QtCore.Qt.AlignRight
                                          | QtCore.Qt.AlignVCenter)
        # accomodate in horizontal layout
        hbox_offset = QHBoxLayout(None)
        hbox_offset.addWidget(self.chk_offset)
        hbox_offset.addWidget(self.az_offset_label)
        hbox_offset.addWidget(self.az_offset_field)
        hbox_offset.addWidget(self.el_offset_label)
        hbox_offset.addWidget(self.el_offset_field)
        hbox_offset.addStretch(1)
        hbox_offset.addWidget(self.offset_button)
        vbox.addLayout(hbox_offset)
        # link to callback
        self.chk_offset.stateChanged.connect(self.chk_offset_state_changed)
        self.chk_offset_state_changed()
        self.offset_button.clicked.connect(self.offset_button_state_changed)
        self.offset_button.setChecked(False)
        self.offset_button_state_changed()

        # add shrink sub form
        self.chkshrink = QCheckBox('Shrink', parent=self)
        self.shrink_button = QPushButton('Expand', parent=self)
        self.shrink_button.setCheckable(True)
        self.shrink_button.toggle()
        self.azshrklbl = QLabel('Az.', parent=self)
        self.azfield = QLineEdit('0.25', parent=self)
        self.elshrklbl = QLabel('El.', parent=self)
        self.elfield = QLineEdit('0.25', parent=self)
        self.azshrklbl.setFixedWidth(40)
        self.elshrklbl.setFixedWidth(40)
        self.azfield.setFixedWidth(80)
        self.elfield.setFixedWidth(80)
        self.azshrklbl.setAlignment(QtCore.Qt.AlignRight
                                    | QtCore.Qt.AlignVCenter)
        self.elshrklbl.setAlignment(QtCore.Qt.AlignRight
                                    | QtCore.Qt.AlignVCenter)
        self.azfield.setAlignment(QtCore.Qt.AlignRight
                                  | QtCore.Qt.AlignVCenter)
        self.elfield.setAlignment(QtCore.Qt.AlignRight
                                  | QtCore.Qt.AlignVCenter)
        hbox_shrink = QHBoxLayout(None)
        hbox_shrink.addWidget(self.chkshrink)
        hbox_shrink.addWidget(self.azshrklbl)
        hbox_shrink.addWidget(self.azfield)
        hbox_shrink.addWidget(self.elshrklbl)
        hbox_shrink.addWidget(self.elfield)
        hbox_shrink.addStretch(1)
        hbox_shrink.addWidget(self.shrink_button)
        self.chkshrink.stateChanged.connect(self.chkshrinkstatechanged)
        self.chkshrinkstatechanged()
        self.shrink_button.clicked.connect(self.shrink_button_state_changed)
        self.shrink_button.setChecked(False)
        self.shrink_button_state_changed()
        vbox.addLayout(hbox_shrink)

        # set fields value
        if filename:
            if type(filename) is list:
                self.filename_field.setText(filename[0])
            else:
                self.filename_field.setText(filename)
        if self.earth_plot:
            self.title_field.setText(self.earth_plot._plot_title)
            self.lon_field.setText(str(self.earth_plot._viewer.longitude()))
            self.lat_field.setText(str(self.earth_plot._viewer.latitude()))
            self.alt_field.setText(str(self.earth_plot._viewer.altitude()))
            # TODO do something for the multiple beams in one file case
            self.cf_field.setText(str(self._patternctlr._conversion_factor))

        # Add Ok/Cancel buttons
        self.lines_button = QPushButton('Lines', self)
        self.lines_button.setEnabled(False)
        apply_button = QPushButton('Apply', self)
        ok_button = QPushButton('OK', self)
        cancel_button = QPushButton('Cancel', self)

        # Place Ok/Cancel button in an horizontal box layout
        hbox2 = QHBoxLayout()
        hbox2.addStretch(1)
        hbox2.addWidget(self.lines_button)
        hbox2.addWidget(apply_button)
        hbox2.addWidget(ok_button)
        hbox2.addWidget(cancel_button)

        # put the button layout in the Vertical Layout
        vbox.addLayout(hbox2)

        # set dialog box layout
        self.setLayout(vbox)

        # connect buttons to actions
        self.lines_button.clicked.connect(self.setlines)
        apply_button.clicked.connect(self.set_pattern_conf)
        ok_button.clicked.connect(lambda: self.set_pattern_conf(close=True))
        cancel_button.clicked.connect(self.close)
        self.cf_field.textChanged.connect(self.refresh_isolevel)

        # Set default field value if pattern object has been provided
        if self._patternctlr:
            self.configure(self._patternctlr)
    # end of __init__

    def configure(self, pattern):
        """This method configure the fields of the dialog with
        the pattern configuration values.
        pattern is the antenna pattern object which provide
        the configuration for this GUI
        """
        utils.trace('in')
        try:
            self.title_field.setText(pattern._conf['title'])
        except KeyError:
            print('pattern.dialog: No title in pattern._conf dictionary.')
        self.lon_field.setText(str(pattern.satellite().longitude()))
        self.lat_field.setText(str(pattern.satellite().latitude()))
        self.alt_field.setText(str(pattern.satellite().altitude()))
        self.yaw_field.setText(
            str(pattern.set(pattern.configure(), 'sat_yaw', 0.0)))
        if pattern._display_slope:
            low = np.amin(pattern.configure()['slopes'])
            high = np.amax(pattern.configure()['slopes'])
            self.isolevel_field.setText('{},{}'.format(low, high))
        else:
            self.isolevel_field.setText(self.get_isolevel())
        self.chk_revert_x.setChecked(pattern._revert_x)
        self.chk_revert_y.setChecked(pattern._revert_y)
        self.chk_rotate.setChecked(pattern._rotated)
        self.chkxpol.setChecked(pattern._use_second_pol)
        self.chkslope.setChecked(pattern._display_slope)
        _shrink = pattern._shrink
        _expand = pattern.set(pattern.configure(), 'expand', False)
        self.chkshrink.setChecked(_shrink | _expand)
        if _shrink != _expand:
            self.shrink_button_state_changed()
        elif _shrink and _expand:
            print("Error: you cannot shrink and expand in the same time.")
        self.chk_offset.setChecked(pattern._offset)
        self.chksurf.setChecked(pattern.set(
            pattern.configure(), 'Color surface', False))
        if pattern._shrink:
            self.azfield.setText(str(pattern._azshrink))
            self.elfield.setText(str(pattern._elshrink))
        if pattern._offset:
            self.az_offset_field.setText(str(pattern._azimuth_offset))
            self.el_offset_field.setText(str(pattern._elevation_offset))
        self.offset_button.setChecked(pattern.set(pattern.configure(),
                                                  'azeloffset',
                                                  True))
        self.offset_button_state_changed()

        # disable use second pol option if second pol not available
        if len(pattern._E_cr):
            self.chkxpol.setEnabled(True)
        else:
            self.chkxpol.setEnabled(False)

        self.refresh_isolevel()
        utils.trace('out')
    # end of configure method

    def get_isolevel(self, pattern=None):
        """Return string formatted isolevel list.
        Each value separated with comma.
        pattern is the antenna pattern
        """
        if self._patternctlr is None:
            return ",".join(str(x) for x in cst.DEFAULT_ISOLEVEL_DBI)
        else:
            return ",".join(str(x) for x in self._patternctlr.get_isolevel())
    # end of function get_isolevel

    def get_cf(self):
        """Return numerical conversion factor from widget field text.
        """
        cf_string = self.cf_field.text()
        try:
            cf_float = float(cf_string)
        except ValueError:
            cf_float = 0.0
        return cf_float
    # end of function get_cf

    def refresh_isolevel(self):
        """Refresh isolevel field regarding polarisation selected and
        absolute isolevel stored in pattern configuration dictionary.
        """
        if self._patternctlr:
            max_co = int(np.max(self._patternctlr.copol()))
            try:
                max_cr = int(np.max(self._patternctlr.cross()))
            except TypeError:
                max_cr = 0
        else:
            max_co = 0
            max_cr = 0

        cf = self.get_cf()
        isolevel = np.array(self._patternctlr._isolevel) - \
            np.max(self._patternctlr._isolevel)
        if self.chkxpol.checkState():
            tmp_str = ",".join(str(x) for x in isolevel + max_cr + cf)
        else:
            tmp_str = ",".join(str(x) for x in isolevel + max_co + cf)

        self.isolevel_field.setText(tmp_str)
    # end of method refresh_isolevel

    def set_pattern_conf(self, close=False):
        utils.trace('in')

        # if no defined pattern attribute return
        if not self._patternctlr:
            return

        config = {}
        config['revert_x'] = self.chk_revert_x.isChecked()
        config['revert_y'] = self.chk_revert_y.isChecked()
        config['rotate'] = self.chk_rotate.isChecked()
        config['use_second_pol'] = self.chkxpol.isChecked()
        config['sat_alt'] = float(self.alt_field.text())
        config['sat_lon'] = float(self.lon_field.text())
        config['sat_lat'] = float(self.lat_field.text())
        config['sat_yaw'] = float(self.yaw_field.text())
        config['display_slope'] = self.chkslope.isChecked()
        config['shrink'] = (self.chkshrink.isChecked()
                            and not self.shrink_button.isChecked())
        config['expand'] = (self.chkshrink.isChecked()
                            and self.shrink_button.isChecked())
        if config['shrink'] or config['expand']:
            config['azshrink'] = float(self.azfield.text())
            config['elshrink'] = float(self.elfield.text())
        config['offset'] = self.chk_offset.isChecked()
        config['azeloffset'] = self.offset_button.isChecked()
        if config['offset']:
            # if offset is defined as azel
            config['azoffset'] = float(self.az_offset_field.text())
            config['eloffset'] = float(self.el_offset_field.text())

        # if multigrd pattern, apply law selected
        if 'law' in self._patternctlr.configure().keys():
            self._patternctlr.apply_law(self.law_id_cmb.currentText())

        if self.chkslope.isChecked():
            config['slopes'] = [float(s)
                                for s in self.isolevel_field.text().split(',')]
        else:
            config['isolevel'] = [float(s)
                                  for s in
                                  self.isolevel_field.text().split(',')]
        config['cf'] = float(self.cf_field.text())
        config['Color surface'] = self.chksurf.isChecked()

        self._patternctlr.configure(config=config)

        self.earth_plot.settitle(self.title_field.text())

        self._patternctlr._conversion_factor = float(self.cf_field.text())

        self.abort = False

        # update plot from GUI input
        self._control.plot()

        # ungrey Lines button
        self.lines_button.setEnabled(True)

        if close:
            self.close()
        utils.trace('out')
    # end of function set_pattern_conf

    def chkshrinkstatechanged(self):
        """Callback deactivating the shrink fields when
        shrink checkbox is unchecked.
        """
        utils.trace()
        self.azfield.setEnabled(self.chkshrink.isChecked())
        self.elfield.setEnabled(self.chkshrink.isChecked())
    # end of callback

    def chk_offset_state_changed(self):
        """Callback deactivating the offset fields when checkbox is unchecked.
        """
        utils.trace()
        self.az_offset_field.setEnabled(self.chk_offset.isChecked())
        self.el_offset_field.setEnabled(self.chk_offset.isChecked())
    # end of callback

    def offset_button_state_changed(self):
        if not self.offset_button.isChecked():
            self.offset_button.setText('Az/El')
            self.az_offset_label.setText('Lon')
            self.el_offset_label.setText('Lat')
        else:
            self.offset_button.setText('Lon/Lat')
            self.az_offset_label.setText('Az')
            self.el_offset_label.setText('El')

    def shrink_button_state_changed(self):
        if not self.shrink_button.isChecked():
            self.shrink_button.setText('Expand')
            self.chkshrink.setText('Shrink')
        else:
            self.shrink_button.setText('Shrink')
            self.chkshrink.setText('Expand')

    def chk_display_slope_changed(self):
        """Callback changing the range displayed in case
        the display slope option is checked.
        """
        utils.trace()
        if self.chkslope.isChecked():
            self.isolevel_field.setText('{},{}'.format(
                self._patternctlr._slope_range[0],
                self._patternctlr._slope_range[1]))
        else:
            self.isolevel_field.setText(self.get_isolevel())

    def cmb_law_changed(self):
        self._patternctlr.apply_law(self.law_id_cmb.currentText())
        self.refresh_isolevel()

    def setlines(self):
        linedlg = LineDialog(self._patternctlr)
        self.setModal(False)
        linedlg.setModal(True)
        # linedlg.show()
        linedlg.exec_()
        self.setModal(True)
Esempio n. 20
0
class Login(QWidget):
    def __init__(self):
        super().__init__()
        self.title = 'Login'
        self.top = 100
        self.left = 100
        self.width = 500
        self.height = 500
        self.log_interface()

    def log_interface(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.top, self.left, self.height, self.width)
        self.dnac = QLineEdit(self)
        self.dnac.setPlaceholderText('dnac center')
        self.dnac.move(100, 100)
        self.user = QLineEdit(self)
        self.user.setPlaceholderText('User Name')
        self.user.move(100, 150)
        self.pw = QLineEdit(self)
        self.pw.setPlaceholderText('Password')
        self.pw.move(100, 200)
        self.combo = QComboBox(self)
        for i in [
                'https://sandboxdnac.cisco.com/',
                'https://sandboxdnac2.cisco.com/'
        ]:
            self.combo.addItem(i)
        self.combo.move(250, 100)
        self.combo.activated[str].connect(self.onchanged)

        self.combo1 = QComboBox(self)
        for i in ['devnetuser']:
            self.combo1.addItem(i)
        self.combo1.move(250, 150)
        self.combo1.activated[str].connect(self.onchanged1)

        self.combo2 = QComboBox(self)
        for i in ['Cisco123!']:
            self.combo2.addItem(i)
        self.combo2.move(250, 200)
        self.combo2.activated[str].connect(self.onchanged2)

        btn = QPushButton('Click to login', self)
        btn.move(100, 300)
        btn.clicked.connect(self.login)

        self.show()

    def onchanged(self, text):
        self.dnac.setText(text)
        self.dnac.adjustSize()

    def onchanged1(self, text):
        self.user.setText(text)
        self.user.adjustSize()

    def onchanged2(self, text):
        self.pw.setText(text)
        self.pw.adjustSize()

    def login(self):
        nextui(self.dnac.text(), self.user.text(), self.pw.text())
        self.SW = SecondWindow(self.dnac.text(), self.user.text(),
                               self.pw.text())
        self.SW.show()
class Voption(QWidget):
    def __init__(self):
        super().__init__()
        self.top = 100
        self.left = 100
        self.width = 1300
        self.height = 840
        self.Rozokar()

    def Rozokar(self):
        self.setWindowTitle("Payroll")
        self.setGeometry(self.left, self.top, self.width, self.height)

        self.label = QLabel(self)
        self.label.setPixmap(QPixmap("new3.jpg"))

        self.line1 = QLineEdit(self)
        self.line1.setFont(QFont('SansSerif', 14))
        self.line1.move(200, 170)
        self.line1.adjustSize()

        self.line2 = QLineEdit(self)
        self.line2.setFont(QFont('SansSerif', 14))
        self.line2.move(550, 170)
        self.line2.adjustSize()

        self.line3 = QLineEdit(self)
        self.line3.setFont(QFont('SansSerif', 14))
        self.line3.move(900, 170)
        self.line3.adjustSize()

        self.line4 = QLineEdit(self)
        self.line4.setFont(QFont('SansSerif', 14))
        self.line4.move(200, 345)
        self.line4.adjustSize()

        self.line5 = QLineEdit(self)
        self.line5.setFont(QFont('SansSerif', 14))
        self.line5.move(550, 345)
        self.line5.adjustSize()

        self.label1 = QLabel(self)
        self.label1.setFont(QtGui.QFont("Arial", 15, QtGui.QFont.Black))
        self.label1.setStyleSheet("color: rgb(255,255,255)")
        self.label1.setText('Employee ID')
        self.label1.adjustSize()
        self.label1.move(200, 120)

        self.label2 = QLabel(self)
        self.label2.setFont(QtGui.QFont("Arial", 15, QtGui.QFont.Black))
        self.label2.setStyleSheet("color: rgb(255,255,255)")
        self.label2.setText('Employee Name')
        self.label2.adjustSize()
        self.label2.move(550, 120)

        self.label3 = QLabel(self)
        self.label3.setFont(QtGui.QFont("Arial", 15, QtGui.QFont.Black))
        self.label3.setStyleSheet("color: rgb(255,255,255)")
        self.label3.setText('Basic Pay')
        self.label3.adjustSize()
        self.label3.move(900, 120)

        self.label4 = QLabel(self)
        self.label4.setFont(QtGui.QFont("Arial", 15, QtGui.QFont.Black))
        self.label4.setStyleSheet("color: rgb(255,255,255)")
        self.label4.setText('Overtime')
        self.label4.adjustSize()
        self.label4.move(200, 300)

        self.label5 = QLabel(self)
        self.label5.setFont(QtGui.QFont("Arial", 15, QtGui.QFont.Black))
        self.label5.setStyleSheet("color: rgb(255,255,255)")
        self.label5.setText('Bonus')
        self.label5.adjustSize()
        self.label5.move(550, 300)

        self.pushbutton1 = QPushButton("Back", self)
        self.pushbutton1.setFont(QFont('SansSerif', 16))
        self.pushbutton1.resize(self.pushbutton1.sizeHint())
        self.pushbutton1.move(680, 480)
        self.pushbutton1.clicked.connect(self.go_to_Weladmin)

        self.pushbutton2 = QPushButton("Submit", self)
        self.pushbutton2.setFont(QFont('SansSerif', 18))
        self.pushbutton2.resize(self.pushbutton2.sizeHint())
        self.pushbutton2.move(1000, 480)
        self.pushbutton2.clicked.connect(self.Submit)

        self.show()

    def go_to_Weladmin(self):
        from Weladmin import Voption
        self.obj = Voption()
        self.obj.show()
        self.close()

    def Submit(self):
        print("submitted Succesfully")
Esempio n. 22
0
class XAbsSysGui(QDialog):
    """ GUI to replace XIDL x_velplot (and more)
    """
    def __init__(self,
                 ispec,
                 abs_sys,
                 parent=None,
                 llist=None,
                 norm=True,
                 vmnx=[-300., 300.] * u.km / u.s,
                 outfil=None):
        """
        spec : Filename or Spectrum1D
        abs_sys : AbsSystem
          Absorption system class
        Norm : bool, optional
          Normalized spectrum?
        """
        from linetools.guis import spec_widgets as ltgs
        super(XAbsSysGui, self).__init__(parent)

        # Initialize
        self.abs_sys = abs_sys
        self.z = self.abs_sys.zabs
        abs_lines = abs_sys.list_of_abslines()
        self.vmnx = vmnx
        if outfil is None:
            self.outfil = 'tmp_abskin.json'
            warnings.warn(
                "Outfil not specified.  Using {:s} as the default".format(
                    self.outfil))
        else:
            self.outfil = outfil
        self.norm = norm

        # Grab the pieces and tie together
        newfont = QtGui.QFont("Times", 10, QtGui.QFont.Bold)
        sys_label = QLabel('Name: \n {:s}'.format(abs_sys.name))
        sys_label.setFont(newfont)
        self.vplt_widg = ltgs.VelPlotWidget(ispec,
                                            self.z,
                                            abs_lines=abs_lines,
                                            llist=llist,
                                            vmnx=self.vmnx,
                                            norm=self.norm)
        self.pltline_widg = ltgl.PlotLinesWidget(
            init_llist=self.vplt_widg.llist, init_z=self.z, edit_z=False)
        #self.pltline_widg.spec_widg = self.vplt_widg

        self.slines = ltgl.SelectedLinesWidget(
            self.vplt_widg.llist[self.vplt_widg.llist['List']],
            init_select=self.vplt_widg.llist['show_line'],
            plot_widget=self.vplt_widg)

        # Connections
        self.pltline_widg.llist_widget.currentItemChanged.connect(
            self.on_llist_change)
        #self.connect(self.pltline_widg.zbox, QtCore.SIGNAL('editingFinished ()'), self.setz)
        self.vplt_widg.canvas.mpl_connect('key_press_event', self.on_key)

        # Outfil
        wbtn = QPushButton(self)
        wbtn.setText('Write')
        wbtn.setAutoDefault(False)
        wbtn.clicked.connect(self.write_out)
        self.out_box = QLineEdit()
        self.out_box.setText(self.outfil)
        self.out_box.textChanged[str].connect(self.set_outfil)
        #self.connect(self.out_box, QtCore.SIGNAL('editingFinished ()'), self.set_outfil)

        #QtCore.pyqtRemoveInputHook()
        #pdb.set_trace()
        #QtCore.pyqtRestoreInputHook()

        # Quit
        buttons = QWidget()
        wqbtn = QPushButton(self)
        wqbtn.setText('Write+Quit')
        wqbtn.setAutoDefault(False)
        wqbtn.clicked.connect(self.write_quit)
        qbtn = QPushButton(self)
        qbtn.setText('Quit')
        qbtn.setAutoDefault(False)
        qbtn.clicked.connect(self.quit)

        # Sizes
        lines_widg = QWidget()
        lines_widg.setMaximumWidth(300)
        lines_widg.setMinimumWidth(200)

        # Layout
        vbox = QVBoxLayout()
        vbox.addWidget(sys_label)
        vbox.addWidget(self.pltline_widg)
        vbox.addWidget(self.slines)
        vbox.addWidget(wbtn)
        vbox.addWidget(self.out_box)
        # Write/Quit buttons
        hbox1 = QHBoxLayout()
        hbox1.addWidget(wqbtn)
        hbox1.addWidget(qbtn)
        buttons.setLayout(hbox1)
        #
        vbox.addWidget(buttons)
        lines_widg.setLayout(vbox)

        hbox = QHBoxLayout()
        hbox.addWidget(self.vplt_widg)
        hbox.addWidget(lines_widg)

        self.setLayout(hbox)
        # Initial draw
        self.vplt_widg.on_draw()

    # Overload, as needed
    def on_key(self, event):
        pass

    # Change list of lines to choose from
    def on_llist_change(self):
        llist = self.pltline_widg.llist
        all_lines = list(llist[llist['List']]._data['wrest'])
        # Set selected
        wrest = [line.wrest for line in self.vplt_widg.abs_lines]
        select = []
        for iwrest in wrest:
            try:
                select.append(all_lines.index(iwrest))
            except ValueError:
                pass
        select.sort()
        # GUIs
        self.vplt_widg.llist['List'] = llist['List']
        self.vplt_widg.llist['show_line'] = select
        self.vplt_widg.idx_line = 0
        self.slines.selected = select
        self.slines.on_list_change(llist[llist['List']])

    # Write
    def set_outfil(self, text):
        self.out_box.setText(text)
        self.out_box.adjustSize()
        self.outfil = str(self.out_box.text())
        print('AbsKin: Will write to {:s}'.format(self.outfil))

    '''
    # Set z from pltline_widg
    def setz(self):
        self.vplt_widg.z = self.pltline_widg.llist['z']
        self.z = self.pltline_widg.llist['z']
        self.vplt_widg.on_draw()
    '''

    def set_new_comps(self):
        """ Generate new components and fill into abs_sys
        Ignores velocity limits when building
        """
        # Add spectrum filename, coord
        abs_lines = self.vplt_widg.abs_lines
        for line in abs_lines:
            line.analy['datafile'] = self.vplt_widg.spec_fil
            line.attrib['coord'] = self.abs_sys.coord
        # Components
        comps = ltiu.build_components_from_abslines(abs_lines, chk_vel=False)
        self.abs_sys._components = comps
        # Return
        return

    # Write
    @pyqtSlot()
    def write_out(self):
        # Update components and spectrum filename
        self.set_new_comps()
        # Dict
        adict = self.abs_sys.to_dict()

        #QtCore.pyqtRemoveInputHook()
        #xdb.set_trace()
        #QtCore.pyqtRestoreInputHook()
        print("Wrote abs_sys to {:s}".format(self.outfil))
        with io.open(self.outfil, 'w', encoding='utf-8') as f:
            f.write(
                json.dumps(adict,
                           sort_keys=True,
                           indent=4,
                           separators=(',', ': ')))

    # Write + Quit
    @pyqtSlot()
    def write_quit(self):
        self.write_out()
        self.flg_quit = 1
        self.done(1)

    # Write + Quit
    @pyqtSlot()
    def quit(self):
        self.flg_quit = 0
        self.done(1)
Esempio n. 23
0
class Ui_MainWindow(object):
    """
    Класс для создания объектов интерфейса 
    """
    def setupUi(self, MainWindow):
        self.setWindowTitle('Клиент')
        self.setFixedSize(280, 220)
        # Set the central widget and the general layout
        self.generalLayout = QVBoxLayout()
        self._centralWidget = QWidget(self)
        self.setCentralWidget(self._centralWidget)
        self._centralWidget.setLayout(self.generalLayout)
        # label rate text
        self.label_rate = QLabel(self)
        self.label_rate.setText('Cтавка \nдисконтирования')
        self.label_rate.move(20, 55)
        self.label_rate.setAlignment(Qt.AlignCenter)

        # value rate line
        self.value_line_edit_rate = QLineEdit(self)
        self.value_line_edit_rate.move(120, 60)
        self.value_line_edit_rate.setText('0.2')
        self.value_line_edit_rate.adjustSize()
        self.value_line_edit_rate.setMaxLength(8)
        pDoubleValidator = QDoubleValidator(self)
        pDoubleValidator.setNotation(QDoubleValidator.StandardNotation)
        pDoubleValidator.setDecimals(4)
        self.value_line_edit_rate.setValidator(pDoubleValidator)

        # label year text
        self.label_year = QLabel(self)
        self.label_year.setText('Год')
        self.label_year.move(20, 85)
        self.label_year.setAlignment(Qt.AlignCenter)
        # value year text
        self.value_line_edit_year = QLineEdit(self)
        self.value_line_edit_year.move(120, 90)
        self.value_line_edit_year.setText('2050')
        self.value_line_edit_year.adjustSize()
        self.value_line_edit_year.setMaxLength(4)
        pIntValidator = QIntValidator(self)
        #pIntValidator.setRange(2020, 2050)
        self.value_line_edit_year.setValidator(pIntValidator)

        # button
        self.button = QPushButton('Расчёт', self)
        #self.button.clicked.connect(self.button1_clicked)
        self.button.resize(200, 32)
        self.button.move(50, 120)

        # Display
        self.display = QLineEdit(self)
        self.display.move(50, 10)
        self.display.resize(200, 32)
        self.display.setAlignment(Qt.AlignLeft)
        self.display.setReadOnly(True)

        # Предупреждение о диапазоне
        self.warning = QLabel(self)
        self.warning.setText('Диапазон:\nГод = [2020,2050], Ставка = [0,1]')
        self.warning.move(30, 170)
        self.warning.resize(200, 40)
Esempio n. 24
0
class CoreWidget(QWidget):

    def get_net(self):
        net = set(self.graphWidget.netlistWidget.netlist.netlist().splitlines())
        return net
    net = property(get_net)

    def get_folder(self):
        return self.graphWidget.netlistWidget.netlist.folder
    folder = property(get_folder)

    def get_label(self):
        return self.titleWidget.label
    label = property(get_label)

    def get_status(self):
        return self.titleWidget.status
    status = property(get_status)

    def __init__(self, graphWidget, parent=None):

        super(CoreWidget, self).__init__(parent)

        self.parameters = {'reduce z': False,
                           'substitute': False}

        self.graphWidget = graphWidget

        self.initUI()

    def initUI(self):

        self.core = Core(self.graphWidget.label)

        self.statusSig = BoolSig()
        self.initSig= NoneSig()

        self.dimsLayout = QHBoxLayout()
        self.dimsLayout.setContentsMargins(0, 0, 0, 0)

        self.storageWidget = DescriptionWidget('Storages', '0', 'Dimension of the state vector')
        self.dissipationWidget = DescriptionWidget('Dissipations', '0', 'Dimension of the dissipation vector')
        self.sourceWidget = DescriptionWidget('Ports', '0', 'Dimension of the inpuut/output vectors')

        self.dimsLayout.addWidget(self.storageWidget)
        self.dimsLayout.addWidget(self.dissipationWidget)
        self.dimsLayout.addWidget(self.sourceWidget)
        self.dimsLayout.addStretch()
        self.dimsLayout.setContentsMargins(0, 0, 0, 0)

        self.dimsWidget = QWidget(self)
        self.dimsWidget.setLayout(self.dimsLayout)

        # ---------------------------------------------------------------------
        # Define Core Actions

        self.buttonsLayout = QHBoxLayout()
        self.buttonsLayout.setContentsMargins(0, 0, 0, 0)

        # Build Action
        build_icon = QIcon(os.path.join(iconspath, 'work.png'))
        self.buildAction = QAction(build_icon,
                                 '&Build PHS Core', self)
        self.buildAction.setShortcut('Ctrl+B')
        self.buildAction.setStatusTip('Build Port-Hamiltonian System equations')
        self.buildAction.triggered.connect(self._build)
        self.buildButton = QPushButton(build_icon, '')
        self.buildButton.setToolTip('Build Port-Hamiltonian System equations')
        self.buildButton.clicked.connect(self._build)
        self.buttonsLayout.addWidget(self.buildButton)

        # Latex export Action
        export_icon = QIcon(os.path.join(iconspath, 'latex.png'))
        self.exportAction = QAction(export_icon,
                                    '&Export LaTeX document', self)
        self.exportAction.setShortcut('Ctrl+L')
        self.exportAction.setStatusTip('Export a LaTeX document that describes the Port-Hamiltonian System')
        self.exportAction.triggered.connect(self._writelatex)
        self.exportButton = QPushButton(export_icon, '')
        self.exportButton.setToolTip('Export a LaTeX document')
        self.exportButton.clicked.connect(self._writelatex)
        self.buttonsLayout.addWidget(self.exportButton)

        # ---------------------------------------------------------------------
        # title widget

        title = 'CORE'

        self.labelWidget = QLineEdit(self.core.label)
        self.labelWidget.adjustSize()
        status_labels = {True: 'OK',
                         False: 'Not OK'}

        self.titleWidget = TitleWidget(title=title,
                                       labelWidget=self.labelWidget,
                                       status_labels=status_labels,
                                       buttonsLayout=self.buttonsLayout)

        # ---------------------------------------------------------------------
        # set parameters

        content = {}

        content['reduce z'] = {'desc': 'Reduce linear dissipations into the R-matrix.',
                               'label': 'Reduce z',
                               'value': self.parameters['reduce z'],
                               'type': 'bool'
                               }

        content['substitute'] = {'desc': 'Substitute all symbols by their numerical value.',
                                 'label': 'Substitute',
                                 'value': self.parameters['substitute'],
                                 'type': 'bool'
                                 }
        tooltip = 'Core parameters'

        self.parametersWidget = ParametersWidget('', content, tooltip)

        # ---------------------------------------------------------------------
        # signals
        self.graphWidget.initSig.sig.connect(self._netlist_init)
        self.graphWidget.statusSig.sig.connect(self._status_changed)
        self.parametersWidget.modifiedSig.sig.connect(self._update_parameters)
        self.titleWidget.labelSignal.sig.connect(self._update_label)

    def _update_parameters(self):
        if not self.parameters == self.parametersWidget.parameters:
            self.parameters.update(self.parametersWidget.parameters)
            self._change_status(False)

    def _update(self):
        self.storageWidget.desc.setText(str(self.core.dims.x()))
        self.dissipationWidget.desc.setText(str(self.core.dims.w()))
        self.sourceWidget.desc.setText(str(self.core.dims.y()))

    def _status_changed(self, s=False):
        if not s:
            self._change_status(s)

    def _change_status(self, s=False):
            self.titleWidget._change_status(s)
            self.statusSig.sig.emit(s)

    def _netlist_init(self):
        label = self.graphWidget.label
        self._update_label(label)
        self.initSig.sig.emit()

    def _update_label(self, label):
        if not self.core.label == label:
            self.graphWidget.graph.label = label
            self.core.label = label
            self.titleWidget._change_label(label)

    def _change_label(self, label):
        self.titleWidget._change_label(label)
        self._update_label(label)

    def _build(self):
        if not self.graphWidget.status:
            self.graphWidget._build()

        if self.graphWidget.status:
            self.core = self.graphWidget.graph.to_core(self.core.label)

            if self.parameters['reduce z']:
                self.core.reduce_z()

            if self.parameters['substitute']:
                self.core.substitute(selfall=True)

            self._update()
            self._change_status(True)

    def _writelatex(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        dialog = QFileDialog()
        filename = os.path.join(self.folder, self.label + '.tex')
        dialog.selectFile(filename)
        fileName, _ = dialog.getSaveFileName(self,
                                             "Save LaTeX file as...",
                                             filename,
                                             "All Files (*);;Latex Files (*.tex)",
                                             "Latex Files (*.tex)",
                                             options=options)
        if not fileName == '':
            folder = filename[:filename.rfind(os.sep)]
            content = netlist2tex(self.graphWidget.netlistWidget.netlist)
            content += graphplot2tex(self.graphWidget.graph,
                                     folder=folder)
            content += core2tex(self.core)
            title = self.core.label
            texdocument(content, fileName, title)
Esempio n. 25
0
class MyWindow(QMainWindow):
    def __init__(self):
        super(MyWindow, self).__init__()
        self.initUI()

    def addCharToList(self, character):
        if not character in self.userList:
            self.userList.append(character)

    def removeCharFromList(self, character):
        if character in self.userList:
            self.userList.remove(character)

    def importChar(self):
        if os.path.isfile('Hero_List.txt'):
            self.numChar = 0
            with open("Hero_List.txt") as file_in:
                lines = []
                for line in file_in:
                    line = line.rstrip('\n')
                    self.addCharToList(line)
                    self.numChar = self.numChar + 1
            self.importStatus.setText("Imported!" + str(self.numChar) +
                                      " characters in the pool")
            self.importStatus.setStyleSheet("color: #32CD32")
            self.importStatus.adjustSize()

        else:
            self.importStatus.setText(
                "Error: please make sure that a 'Hero_List.txt' file is in your directory"
            )
            self.importStatus.setStyleSheet("color: #FF0000")
            self.importStatus.adjustSize()

    def initUI(self):
        self.controls = QWidget()
        self.controlsLayout = QVBoxLayout()

        # read json file and get jepg
        try:
            with open('e7dbherodata.json') as json_file:
                self.data = json.load(json_file)
        except:
            error_dialog = QtWidgets.QErrorMessage()
            error_dialog.showMessage("Missing e7assets.json file")
            error_dialog.exec_()

        self.userList = []

        # list of characters, separated by star grade
        characters5 = (
            'Alencia', 'Ambitious Tywin', 'Apocalypse Ravi', 'Aramintha',
            'Arbiter Vildred', 'Baal & Sezan', 'Baiken', 'Basar', 'Bellona',
            'Blood Moon Haste', 'Briar Witch Iseria', 'Cecilia', 'Celine',
            'Cerise', 'Cermia', 'Charles', 'Charlotte', 'Chloe', 'Choux',
            'Dark Corvus', 'Desert Jewel Basar', 'Destina', 'Diene', 'Dizzy',
            'Elena', 'Elphelt', 'Ervalen', 'Faithless Lidica',
            'Fallen Cecilia', 'Flan', 'Haste', 'Holiday Yufine', 'Iseria',
            'Judge Kise', 'Kawerik', 'Kayron', 'Ken', 'Kise', 'Krau', 'Landy',
            'Last Rider Krau', 'Lidica', 'Lilias', 'Lilibet',
            'Little Queen Charlotte', 'Ludwig', 'Luluca', 'Luna', 'Maid Chloe',
            'Martial Artist Ken', 'Melissa', 'Mui', 'Operator Sigret', 'Pavel',
            'Ravi', 'Ray', 'Remnant Violet', 'Roana', 'Ruele of Light',
            'Sage Baal & Sezan', 'Seaside Bellona', 'Sez', 'Sigret',
            'Silver Blade Aramintha', 'Sol', 'Specimen Sez',
            'Specter Tenebria', 'Tamarinne', 'Tenebria', 'Top Model Luluca',
            'Tywin', 'Vildred', 'Violet', 'Vivian', 'Yufine', 'Yuna', 'Zeno',
            'Fairytale Tenebria', 'Mort')
        characters4 = ('Achates', 'Angelica', 'Armin', 'Assassin Cartuja',
                       'Assassin Cidd', 'Assassin Coli', 'Auxiliary Lots',
                       'Benevolent Romann', 'Blaze Dingo', 'Blood Blade Karin',
                       'Cartuja', 'Celestial Mercedes', 'Challenger Dominiel',
                       'Champion Zerato', 'Cidd', 'Clarissa', 'Coli', 'Corvus',
                       'Crescent Moon Rin', 'Crimson Armin', 'Crozet', 'Dingo',
                       'Dominiel', 'Fighter Maya', 'Free Spirit Tieria',
                       'Furious', 'General Purrgis', 'Guider Aither', 'Karin',
                       'Khawana', 'Khawazu', 'Kitty Clarissa', 'Kizuna AI',
                       'Leo', 'Lots', 'Maya', 'Mercedes', 'Purrgis', 'Rin',
                       'Roaming Warrior Leo', 'Romann', 'Rose', 'Schuri',
                       'Serila', 'Shadow Rose', 'Shooting Star Achates',
                       'Silk', 'Sinful Angelica', 'Surin', 'Tempest Surin',
                       'Troublemaker Crozet', 'Wanderer Silk',
                       'Watcher Schuri', 'Zerato')
        characters3 = ('Adlay', 'Adventurer Ras', 'Ainos', 'Ains', 'Aither',
                       'Alexa', 'All-Rounder Wanda', 'Angelic Montmorancy',
                       'Arowell', 'Azalea', 'Bask', 'Batisse',
                       'Butcher Corps Inquisitor', 'Captain Rikoris',
                       'Carmainerose', 'Carrot', 'Celeste', 'Chaos Inquisitor',
                       'Chaos Sect Ax', 'Church of Ilryos Axe',
                       'Commander Lorina', 'Doll Maker Pearlhorizon', 'Doris',
                       'Eaton', 'Elson', 'Enott', 'Falconer Kluri', 'Glenn',
                       'Gloomyrain', 'Godmother', 'Gunther', 'Hataan', 'Hazel',
                       'Helga', 'Hurado', 'Ian', 'Jecht', 'Jena', 'Judith',
                       'Kikirat v2', 'Kiris', 'Kluri', 'Lena', 'Lorina',
                       'Magic Scholar Doris', 'Mascot Hazel',
                       'Mercenary Helga', 'Mirsa', 'Mistychain', 'Montmorancy',
                       'Mucacha', 'Nemunas', 'Otillie', 'Pearlhorizon',
                       'Pyllis', 'Ras', 'Requiemroar', 'Researcher Carrot',
                       'Righteous Thief Roozid', 'Rikoris', 'Rima', 'Roozid',
                       'Sonia', 'Sven', 'Taranor Guard', 'Taranor Royal Guard',
                       'Tieria', 'Wanda', 'Zealot Carmainerose')
        charactersAll = characters5 + characters4 + characters3

        self.widgets = []

        for name in charactersAll:
            item = AddRemoveWidget(name)
            # attribute functions to each button
            item.button_add.clicked.connect(
                lambda _, name=name: self.addCharToList(name))
            item.button_remove.clicked.connect(
                lambda _, name=name: self.removeCharFromList(name))
            self.controlsLayout.addWidget(item)
            self.widgets.append(item)

        spacer = QSpacerItem(1, 1, QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.controlsLayout.addItem(spacer)
        self.controls.setLayout(self.controlsLayout)

        self.setWindowTitle("E7 Ultimate Bravery")
        self.setGeometry(200, 200, 1024, 680)

        self.label1 = QtWidgets.QLabel(self)
        self.label1.setText("<h1>Epic 7 Roulette</h1>")
        self.label1.adjustSize()
        self.label1.move(10, 15)

        self.label2 = QtWidgets.QLabel(self)
        self.label2.setText("Add Characters to Roulette")
        self.label2.move(10, 55)
        self.label2.adjustSize()

        self.label3 = QtWidgets.QLabel(self)
        self.label3.setText("<h1>Team 1:</h1>")
        self.label3.adjustSize()
        self.label3.move(540, 60)

        self.label4 = QtWidgets.QLabel(self)
        self.label4.setText("")
        self.label4.move(540, 85)

        self.label5 = QtWidgets.QLabel(self)
        self.label5.setText("")
        self.label5.move(650, 85)

        self.label6 = QtWidgets.QLabel(self)
        self.label6.setText("")
        self.label6.move(760, 85)

        self.label7 = QtWidgets.QLabel(self)
        self.label7.setText("<h1>Team 2:</h1>")
        self.label7.adjustSize()
        self.label7.move(540, 200)

        self.label8 = QtWidgets.QLabel(self)
        self.label8.setText("")
        self.label8.move(540, 225)

        self.label9 = QtWidgets.QLabel(self)
        self.label9.setText("")
        self.label9.move(650, 225)

        self.label10 = QtWidgets.QLabel(self)
        self.label10.setText("")
        self.label10.move(760, 225)

        self.image = QImage()

        self.scroll = QScrollArea()
        self.scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.scroll.setWidgetResizable(False)
        self.scroll.setWidget(self.controls)

        self.searchBar = QLineEdit()
        self.searchBar.adjustSize()
        self.searchBar.textChanged.connect(self.updateDisplay)

        self.completer = QCompleter(charactersAll)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.searchBar.setCompleter(self.completer)

        container = QWidget()
        containerLayout = QVBoxLayout()
        containerLayout.addWidget(self.searchBar)
        containerLayout.addWidget(self.scroll)
        containerLayout.setContentsMargins(10, 85, 0, 0)

        container.setLayout(containerLayout)
        container.setFixedSize(400, 600)
        self.setCentralWidget(container)

        self.b1 = QtWidgets.QPushButton(self)
        self.b1.setText("Roll")
        self.b1.setGeometry(10, 610, 390, 40)
        self.b1.clicked.connect(self.RandRoll)

        self.b2 = QtWidgets.QPushButton(self)
        self.b2.setText("Import")
        self.b2.setGeometry(250, 25, 100, 20)
        self.b2.clicked.connect(self.importChar)

        self.importStatus = QtWidgets.QLabel(self)
        self.importStatus.setText("")
        self.importStatus.move(360, 30)

    def updateDisplay(self, text):
        for widget in self.widgets:
            if text.lower() in widget.name.lower():
                widget.show()
            else:
                widget.hide()

    def displayImage(self, url, label):
        self.image.loadFromData(requests.get(url).content)
        label.setPixmap(
            QtGui.QPixmap(self.image).scaled(100, 100, Qt.KeepAspectRatio))
        label.adjustSize()

    def RandRoll(self):

        if (len(self.userList)) < 6:
            self.label4.setText("<h1>Not enough characters in pool</h1>")
            self.label4.setStyleSheet("color: #FF0000")
            self.label4.adjustSize()
            return

        #create a separate list to save "names" for rerolls
        self.tempList = []

        selectedString = random.choice(self.userList)
        self.tempList.append(selectedString)
        url_img = self.data[selectedString]['assets']['icon']
        self.displayImage(url_img, self.label4)
        self.userList.remove(selectedString)

        selectedString = random.choice(self.userList)
        self.tempList.append(selectedString)
        url_img = self.data[selectedString]['assets']['icon']
        self.displayImage(url_img, self.label5)
        self.userList.remove(selectedString)

        selectedString = random.choice(self.userList)
        self.tempList.append(selectedString)
        url_img = self.data[selectedString]['assets']['icon']
        self.displayImage(url_img, self.label6)
        self.userList.remove(selectedString)

        selectedString = random.choice(self.userList)
        self.tempList.append(selectedString)
        url_img = self.data[selectedString]['assets']['icon']
        self.displayImage(url_img, self.label8)
        self.userList.remove(selectedString)

        selectedString = random.choice(self.userList)
        self.tempList.append(selectedString)
        url_img = self.data[selectedString]['assets']['icon']
        self.displayImage(url_img, self.label9)
        self.userList.remove(selectedString)

        selectedString = random.choice(self.userList)
        self.tempList.append(selectedString)
        url_img = self.data[selectedString]['assets']['icon']
        self.displayImage(url_img, self.label10)
        self.userList.remove(selectedString)

        # add back all "removed" names into userList
        self.userList = self.userList + self.tempList
class Addemp(QWidget):

    def __init__(self):
        super().__init__()
        self.top=100
        self.left=100
        self.width=1300
        self.height=840
        self.Emp_Detail()

    def Emp_Detail(self):
        self.setWindowTitle("Add Employee")
        self.setGeometry(self.left,self.top,self.width,self.height)

        self.label = QLabel(self)
        self.label.setPixmap(QPixmap("new3.jpg"))

        self.label1 = QLabel(self)
        self.label1.setFont(QtGui.QFont("Arial", 15, QtGui.QFont.Black))
        self.label1.setStyleSheet("color: rgb(255,255,255)")
        self.label1.setText('Employee Id')
        self.label1.adjustSize()
        self.label1.move(200, 125)

        self.label2 = QLabel(self)
        self.label2.setFont(QtGui.QFont("Arial", 15, QtGui.QFont.Black))
        self.label2.setStyleSheet("color: rgb(255,255,255)")
        self.label2.setText('Full Name')
        self.label2.adjustSize()
        self.label2.move(550, 125)

        self.label3 = QLabel(self)
        self.label3.setFont(QtGui.QFont("Arial", 15, QtGui.QFont.Black))
        self.label3.setStyleSheet("color: rgb(255,255,255)")
        self.label3.setText('Address')
        self.label3.adjustSize()
        self.label3.move(900, 125)

        self.label4 = QLabel(self)
        self.label4.setFont(QtGui.QFont("Arial", 15, QtGui.QFont.Black))
        self.label4.setStyleSheet("color: rgb(255,255,255)")
        self.label4.setText('Contact')
        self.label4.adjustSize()
        self.label4.move(200, 300)

        self.label5 = QLabel(self)
        self.label5.setFont(QtGui.QFont("Arial", 15, QtGui.QFont.Black))
        self.label5.setStyleSheet("color: rgb(255,255,255)")
        self.label5.setText('Email')
        self.label5.adjustSize()
        self.label5.move(550, 300)

        self.label6 = QLabel(self)
        self.label6.setFont(QtGui.QFont("Arial", 15, QtGui.QFont.Black))
        self.label6.setStyleSheet("color: rgb(255,255,255)")
        self.label6.setText('Designation')
        self.label6.adjustSize()
        self.label6.move(900, 300)

        self.label7 = QLabel(self)
        self.label7.setFont(QtGui.QFont("Arial", 15, QtGui.QFont.Black))
        self.label7.setStyleSheet("color: rgb(255,255,255)")
        self.label7.setText('Department')
        self.label7.adjustSize()
        self.label7.move(200, 450)

        self.label8 = QLabel(self)
        self.label8.setFont(QtGui.QFont("Arial", 15, QtGui.QFont.Black))
        self.label8.setStyleSheet("color: rgb(255,255,255)")
        self.label8.setText('Joined Date')
        self.label8.adjustSize()
        self.label8.move(550, 450)

        self.label9 = QLabel(self)
        self.label9.setFont(QtGui.QFont("Arial", 15, QtGui.QFont.Black))
        self.label9.setStyleSheet("color: rgb(255,255,255)")
        self.label9.setText('Worked Hour')
        self.label9.adjustSize()
        self.label9.move(900, 450)

        self.line1 = QLineEdit(self)
        self.line1.setFont(QFont('SansSerif', 14))
        self.line1.move(200, 170)
        self.line1.adjustSize()

        self.line2 = QLineEdit(self)
        self.line2.setFont(QFont('SansSerif', 14))
        self.line2.move(550, 170)
        self.line2.adjustSize()

        self.line3 = QLineEdit(self)
        self.line3.setFont(QFont('SansSerif', 14))
        self.line3.move(900, 170)
        self.line3.adjustSize()

        self.line4 = QLineEdit(self)
        self.line4.setFont(QFont('SansSerif', 14))
        self.line4.move(200, 345)
        self.line4.adjustSize()

        self.line5 = QLineEdit(self)
        self.line5.setFont(QFont('SansSerif', 14))
        self.line5.move(550, 345)
        self.line5.adjustSize()

        self.line6 = QLineEdit(self)
        self.line6.setFont(QFont('SansSerif', 14))
        self.line6.move(900, 345)
        self.line6.adjustSize()

        self.line7 = QLineEdit(self)
        self.line7.setFont(QFont('SansSerif', 14))
        self.line7.move(200, 495)
        self.line7.adjustSize()

        self.line8 = QLineEdit(self)
        self.line8.setFont(QFont('SansSerif', 14))
        self.line8.move(550, 495)
        self.line8.adjustSize()

        self.line9 = QLineEdit(self)
        self.line9.setFont(QFont('SansSerif', 14))
        self.line9.move(900, 495)
        self.line9.adjustSize()

        self.pushbutton1 = QPushButton("  Back", self)
        self.pushbutton1.setFont(QFont('SansSerif', 18))
        self.pushbutton1.setIcon(QIcon(QPixmap("back.png")))
        self.pushbutton1.resize(self.pushbutton1.sizeHint())
        self.pushbutton1.move(600, 600)
        self.pushbutton1.clicked.connect(self.goback)

        self.pushbutton2 = QPushButton("Submit", self)
        self.pushbutton2.setFont(QFont('SansSerif', 18))
        self.pushbutton2.resize(self.pushbutton2.sizeHint())
        self.pushbutton2.move(1000, 600)
        self.pushbutton2.clicked.connect(self.Submit)

        self.show()

    def goback(self):
        from Weladmin import Voption
        self.obj=Voption()
        self.obj.show()
        self.close()

    def Submit(self):
        print("submitted Succesfully")
Esempio n. 27
0
    def initUI(self):
        #set width of main window (X, Y , WIDTH, HEIGHT)
        windowWidth = 800
        windowHeight = 500
        self.setGeometry(350, 50, windowWidth, windowHeight)

        #define a font for the title of the UI
        titleFont = QtGui.QFont()
        titleFont.setBold(True)
        titleFont.setPointSize(12)

        #define a font for the buttons of the UI
        buttonFont = QtGui.QFont()
        buttonFont.setBold(False)
        buttonFont.setPointSize(10)

        mainGrid = QGridLayout()
        self.setLayout(mainGrid)

        #create a label at the top of the window so we know what the window does
        topTextLabel = QLabel('Lenses Control', self)
        topTextLabel.setAlignment(QtCore.Qt.AlignCenter)
        topTextLabel.setFixedHeight(50)
        topTextLabel.setWordWrap(True)
        topTextLabel.setFont(titleFont)
        mainGrid.addWidget(topTextLabel, 0, 0, 1, 10)

        #add labels for condenser 1, condenser 2, intermediate 1
        C1SetLabel = QLabel('Condenser 1 Setting')
        mainGrid.addWidget(C1SetLabel, 1, 0)

        C2SetLabel = QLabel('Condenser 2 Setting')
        mainGrid.addWidget(C2SetLabel, 2, 0)

        I1SetLabel = QLabel('Intermediate 1 Setting')
        mainGrid.addWidget(I1SetLabel, 3, 0)

        C1GetLabel = QLabel('Condenser 1 Feedback')
        mainGrid.addWidget(C1GetLabel, 4, 0)

        C2GetLabel = QLabel('Condenser 2 Feedback')
        mainGrid.addWidget(C2GetLabel, 5, 0)

        I1GetLabel = QLabel('Intermediate 1 Feedback')
        mainGrid.addWidget(I1GetLabel, 6, 0)

        #add edit boxes to the right of the setting labels
        C1Set = QLineEdit(self)
        C1Set.setText('0')
        C1Set.setFixedWidth(100)
        C1Set.setAlignment(QtCore.Qt.AlignCenter)
        C1Set.textChanged.connect(
            lambda: Hardware.IO.setAnalog('C1', C1Set.text()))
        mainGrid.addWidget(C1Set, 1, 1)

        C2Set = QLineEdit()
        C2Set.setText('0')
        C2Set.setFixedWidth(100)
        C2Set.setAlignment(QtCore.Qt.AlignCenter)
        C1Set.textChanged.connect(
            lambda: Hardware.IO.setAnalog('C2', C2Set.text()))
        mainGrid.addWidget(C2Set, 2, 1)

        I1Set = QLineEdit()
        I1Set.setText('0')
        I1Set.setFixedWidth(100)
        I1Set.setAlignment(QtCore.Qt.AlignCenter)
        C1Set.textChanged.connect(
            lambda: Hardware.IO.setAnalog('I1', I1Set.text()))
        mainGrid.addWidget(I1Set, 3, 1)

        #add Feedback Labels and update them to display analog inputs from corresponding channels
        C1Get = QLineEdit('')
        C1Get.setReadOnly(True)
        C1Get.setFixedWidth(100)
        mainGrid.addWidget(C1Get, 4, 1)
        C1Get.adjustSize()

        C2Get = QLineEdit('')
        C2Get.setReadOnly(True)
        C2Get.setFixedWidth(100)
        mainGrid.addWidget(C2Get, 5, 1)
        C2Get.adjustSize()

        I1Get = QLineEdit('')
        I1Get.setReadOnly(True)
        I1Get.setFixedWidth(100)
        mainGrid.addWidget(I1Get, 6, 1)
        I1Get.adjustSize()

        DO1 = QCheckBox('Digital output 1')
        DO1.stateChanged.connect(
            lambda: Hardware.IO.setDigital("Out1", DO1.isChecked()))
        mainGrid.addWidget(DO1, 7, 1)

        self.displayPlot = TimePlot.main()
        self.displayPlot.setupPlot(3, 'Lens Voltages', 'Voltage [V]',
                                   ['C1', 'C2', 'I1'])
        mainGrid.addWidget(self.displayPlot, 1, 2, 6, 5)

        #actually add the main overall grid to the popup window
        self.setLayout(mainGrid)

        #name the window
        self.setWindowTitle('Lens Settings')

        self.updateTimer = QtCore.QTimer()
        self.updateTimer.timeout.connect(lambda: self.updateFeedback(
            [C1Get, C2Get, I1Get], ['C1', 'C2', 'I1']))
        self.updateTimer.start(10)
Esempio n. 28
0
class LoginWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        # Daig 이미지
        daig_img = QPixmap('./local_data/daig_img.png')  # 비율 10:4
        self.img_container = QLabel(self)
        self.img_container.setPixmap(QPixmap(daig_img))
        self.img_container.setScaledContents(True)
        self.img_container.setMaximumSize(300, 120)
        self.img_container.move(70, 20)

        # 로그인 버튼
        self.login = QPushButton('Login', self)
        self.login.resize(80, 80)
        self.login.move(300, 170)

        setLoginButtonStyle(self.login)

        # 회원가입 버튼
        self.sign_up = QPushButton('회원가입', self)
        self.sign_up.move(30, 265)
        setButtonStyle(self.sign_up)
        self.sign_up.setFixedWidth(340)

        # 아이디 찾기 버튼
        self.find_id = QPushButton('아이디 찾기', self)
        self.find_id.move(30, 305)
        setButtonStyle(self.find_id)
        self.find_id.setFixedWidth(340)

        # 비밀번호 찾기 버튼
        self.find_pwd = QPushButton('비밀번호 찾기', self)
        self.find_pwd.move(30, 345)
        setButtonStyle(self.find_pwd)
        self.find_pwd.setFixedWidth(340)

        # 아이디, 비밀번호 알리기
        self.label_id = QLabel('ID ', self)
        self.label_id.move(20, 185)
        font_id = self.label_id.font()
        font_id.setBold(True)
        font_id.setPointSize(20)
        setLabelStyle(self.label_id)

        self.label_pwd = QLabel('Password ', self)
        self.label_pwd.move(20, 225)
        font_pwd = self.label_pwd.font()
        font_pwd.setBold(True)
        font_pwd.setPointSize(20)
        setLabelStyle(self.label_pwd)

        # 아이디, 비밀번호 작성
        self.id = QLineEdit(self)
        self.id.move(100, 180)
        setEditStandard(self.id, 100, 180, '아이디')
        self.id.setFixedWidth(185)

        self.pwd = QLineEdit(self)
        self.pwd.setEchoMode(QLineEdit.Password)
        self.pwd.move(100, 220)
        self.pwd.setFixedWidth(185)
        setEditStandard(self.pwd, 100, 220, '비밀번호')

    # 아이디, 비밀번호 창
    def onChanged(self, text):
        self.id.setText(text)
        self.id.adjustSize()
        self.pwd.setText(text)
        self.pwd.adjustSize()

    def onClickLogin(self):
        sender_data = {"username": self.id.text(), "password": self.pwd.text()}
        print(sender_data)
        res = login_req(sender_data)
        print(res)
        if (res["is_successful"] == True):
            set_auth_header(res["auth"])
            print('set auth')
            return res["auth"]
        else:
            QMessageBox.about(self, 'DAIG', res["message"])
            return False
Esempio n. 29
0
class MainWindow(QWidget):
    def __init__(self, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)
        with open("photoconfig.yaml", 'r') as stream:
            self.config = yaml.full_load(stream)
        realpath = os.path.dirname(os.path.realpath(__file__))
        for (key, val) in self.config['paths'].items():
            self.config['paths'][key] = os.path.join(realpath, val)
        self.make_gui()
        self.foto_thread = FotoThread(config=self.config)
        # connects the pyqtSignal with get_email method
        self.foto_thread.signal.connect(self.get_email)
        self.foto_thread.start()

    def get_email(self):
        log.append("getting email")
        # get email from QEntry
        email = self.line.text().strip()
        self.line.setText("")
        if email:
            # use email as filename with images paths
            newaddr = os.path.join(self.config['paths']['addr'], email)
            with open(newaddr, 'a') as outfile:
                with open(self.config['paths']['piclist']) as infile:
                    outfile.write(infile.read())
            os.remove(self.config['paths']['piclist'])
        log.append(email)

    def on_button_press(self):
        sender = self.sender()
        if sender.text() == "<":
            self.line.backspace()
        else:
            self.line.insert(sender.text())

    def make_gui(self):
        self.name = None
        self.setStyleSheet(
            "color:white; background-color: black; border-style: none")
        self.showFullScreen()
        self.setCursor(Qt.BlankCursor)

        stretchval = 10

        self.line = QLineEdit()
        self.line.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.line.setAlignment(Qt.AlignCenter)
        self.line.adjustSize()
        self.line.setStyleSheet(
            "font: bold; font-size: 46px; font-family: Arial")
        self.line.setCursor(Qt.BlankCursor)
        self.line.setMinimumWidth(self.config['camera']['screen_wh'][0])

        hbox = QHBoxLayout()
        hbox.addWidget(self.line, stretchval, Qt.AlignCenter)
        hbox.setAlignment(Qt.AlignCenter)
        hbox.setContentsMargins(0, self.config['camera']['screen_wh'][1] / 12,
                                0, self.config['camera']['screen_wh'][1] / 12)

        vbox = QVBoxLayout()
        vbox.addLayout(hbox, stretchval)
        vbox.setContentsMargins(0, 0, 0, 0)

        keys = [
            ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '<'],
            ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '+'],
            ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', '_', '-'],
            ['@', 'z', 'x', 'c', 'v', 'b', 'n', 'm', '.', ''],
        ]

        for row in keys:
            rowlayout = QHBoxLayout()
            rowlayout.setContentsMargins(0, 0, 0, 0)
            for letter in row:
                klwidget = QPushButton(letter)
                klwidget.clicked.connect(self.on_button_press)
                klwidget.setStyleSheet("QPushButton {padding: 0;}")
                klwidget.setStyleSheet("font: bold; font-size: 44px")
                klwidget.setMinimumWidth(
                    self.config['camera']['screen_wh'][1] / 12)
                klwidget.setMinimumHeight(
                    self.config['camera']['screen_wh'][1] / 6)
                klwidget.adjustSize()
                rowlayout.addWidget(klwidget, stretchval, Qt.AlignBottom)
            vbox.addLayout(rowlayout, stretchval)

        self.setLayout(vbox)
class Addemp(QWidget):
    def __init__(self):
        super().__init__()
        self.top = 100
        self.left = 100
        self.width = 1300
        self.height = 840
        self.Emp_Detail()

    def Emp_Detail(self):
        self.setWindowTitle("Add Employee")
        self.setGeometry(self.left, self.top, self.width, self.height)

        self.label1 = QLabel(self)
        self.label1.setFont(QFont('SansSerif', 14))
        self.label1.setText('Employee Id')
        self.label1.adjustSize()
        self.label1.move(50, 25)

        self.label2 = QLabel(self)
        self.label2.setFont(QFont('SansSerif', 14))
        self.label2.setText('Full Name')
        self.label2.adjustSize()
        self.label2.move(320, 25)

        self.label3 = QLabel(self)
        self.label3.setFont(QFont('SansSerif', 14))
        self.label3.setText('Address')
        self.label3.adjustSize()
        self.label3.move(590, 25)

        self.label4 = QLabel(self)
        self.label4.setFont(QFont('SansSerif', 14))
        self.label4.setText('Contact')
        self.label4.adjustSize()
        self.label4.move(50, 150)

        self.label5 = QLabel(self)
        self.label5.setFont(QFont('SansSerif', 14))
        self.label5.setText('Email')
        self.label5.adjustSize()
        self.label5.move(320, 150)

        self.label6 = QLabel(self)
        self.label6.setFont(QFont('SansSerif', 14))
        self.label6.setText('Designation')
        self.label6.adjustSize()
        self.label6.move(590, 150)

        self.label7 = QLabel(self)
        self.label7.setFont(QFont('SansSerif', 14))
        self.label7.setText('Department')
        self.label7.adjustSize()
        self.label7.move(50, 275)

        self.label8 = QLabel(self)
        self.label8.setFont(QFont('SansSerif', 14))
        self.label8.setText('Joined Date')
        self.label8.adjustSize()
        self.label8.move(320, 275)

        self.label9 = QLabel(self)
        self.label9.setFont(QFont('SansSerif', 14))
        self.label9.setText('Worked Hour')
        self.label9.adjustSize()
        self.label9.move(590, 275)

        self.line1 = QLineEdit(self)
        self.line1.setFont(QFont('SansSerif', 14))
        self.line1.move(50, 65)
        self.line1.adjustSize()

        self.line2 = QLineEdit(self)
        self.line2.setFont(QFont('SansSerif', 14))
        self.line2.move(320, 65)
        self.line2.adjustSize()

        self.line3 = QLineEdit(self)
        self.line3.setFont(QFont('SansSerif', 14))
        self.line3.move(590, 65)
        self.line3.adjustSize()

        self.line4 = QLineEdit(self)
        self.line4.setFont(QFont('SansSerif', 14))
        self.line4.move(50, 190)
        self.line4.adjustSize()

        self.line5 = QLineEdit(self)
        self.line5.setFont(QFont('SansSerif', 14))
        self.line5.move(320, 190)
        self.line5.adjustSize()

        self.line6 = QLineEdit(self)
        self.line6.setFont(QFont('SansSerif', 14))
        self.line6.move(590, 190)
        self.line6.adjustSize()

        self.line7 = QLineEdit(self)
        self.line7.setFont(QFont('SansSerif', 14))
        self.line7.move(50, 315)
        self.line7.adjustSize()

        self.line8 = QLineEdit(self)
        self.line8.setFont(QFont('SansSerif', 14))
        self.line8.move(320, 315)
        self.line8.adjustSize()

        self.line9 = QLineEdit(self)
        self.line9.setFont(QFont('SansSerif', 14))
        self.line9.move(590, 315)
        self.line9.adjustSize()

        self.pushbutton1 = QPushButton("Back", self)
        self.pushbutton1.setFont(QFont('SansSerif', 14))
        self.pushbutton1.resize(self.pushbutton1.sizeHint())
        self.pushbutton1.move(150, 460)
        self.pushbutton1.clicked.connect(self.goback)

        self.pushbutton2 = QPushButton("Submit", self)
        self.pushbutton2.setFont(QFont('SansSerif', 14))
        self.pushbutton2.resize(self.pushbutton2.sizeHint())
        self.pushbutton2.move(350, 460)
        self.pushbutton2.clicked.connect(self.Submit)

        self.show()

    def goback(self):
        from Weladmin import Voption
        self.obj = Voption()
        self.obj.show()
        self.close()

    def Submit(self):
        print("submitted Succesfully")
Esempio n. 31
0
class MethodWidget(QWidget):
    def get_net(self):
        return self.coreWidget.net

    net = property(get_net)

    def get_folder(self):
        return self.coreWidget.folder

    folder = property(get_folder)

    def get_label(self):
        return self.titleWidget.label

    label = property(get_label)

    def get_core(self):
        return self.coreWidget.core

    core = property(get_core)

    def get_status(self):
        return self.titleWidget.status

    status = property(get_status)

    def __init__(self, coreWidget, parent=None):

        super(MethodWidget, self).__init__(parent)

        self.parameters = {
            'grad': 'discret',  # In {‘discret’, ‘theta’, ‘trapez’}
            'theta': 0.,  # Theta-scheme for the structure
            'split': True,  # split implicit from explicit part
        }

        self.coreWidget = coreWidget

        self.initUI()

    def initUI(self):

        self.method = self.coreWidget.core.to_method()

        self.statusSig = BoolSig()
        self.initSig = NoneSig()

        dimsLayout = QHBoxLayout()
        dimsLayout.setContentsMargins(0, 0, 0, 0)

        self.expliciteWidget = DescriptionWidget(
            'Explicit', '0', 'Dimension of the explict update')
        self.impliciteWidget = DescriptionWidget(
            'Implicit', '0', 'Dimension of the implict update')

        dimsLayout.addWidget(self.expliciteWidget)
        dimsLayout.addWidget(self.impliciteWidget)
        dimsLayout.addStretch()

        # ---------------------------------------------------------------------
        # Define Method Actions

        buttonsLayout = QHBoxLayout()
        buttonsLayout.setContentsMargins(0, 0, 0, 0)

        # Build Action
        build_icon = QIcon(os.path.join(iconspath, 'work.png'))
        self.buildAction = QAction(build_icon, '&Build numerical Method', self)
        self.buildAction.setShortcut('Ctrl+B')
        self.buildAction.setStatusTip('Build numerical method equations')
        self.buildAction.triggered.connect(self._build)
        self.buildButton = QPushButton(build_icon, '')
        self.buildButton.setToolTip('Build numerical method equations')
        self.buildButton.clicked.connect(self._build)
        buttonsLayout.addWidget(self.buildButton)

        # Latex export Action
        export_icon = QIcon(os.path.join(iconspath, 'latex.png'))
        self.exportAction = QAction(export_icon, '&Export LaTeX document',
                                    self)
        self.exportAction.setShortcut('Ctrl+L')
        self.exportAction.setStatusTip(
            'Export a LaTeX document that describes the Port-Hamiltonian System'
        )
        self.exportAction.triggered.connect(self._build)
        self.exportButton = QPushButton(export_icon, '')
        self.exportButton.setToolTip('Export a LaTeX document')
        self.exportButton.clicked.connect(self._writelatex)
        buttonsLayout.addWidget(self.exportButton)

        # ---------------------------------------------------------------------
        # title widget

        title = 'METHOD'

        self.labelWidget = QLineEdit(self.core.label)
        self.labelWidget.adjustSize()

        status_labels = {True: 'OK', False: 'Not OK'}

        self.titleWidget = TitleWidget(title=title,
                                       labelWidget=self.labelWidget,
                                       status_labels=status_labels,
                                       buttonsLayout=buttonsLayout)

        # ---------------------------------------------------------------------
        # set parameters

        content = {}

        content['grad'] = {
            'desc': 'Discrete Evaluation of Hamiltonian gradient.',
            'label': 'Gradient',
            'value': self.parameters['grad'],
            'type': 'sel',
            'choices': ['discret', 'theta', 'trapez']
        }
        content['theta'] = {
            'desc': 'Theta scheme (0=explicit, 0.5=midpoint, 1=implicit).',
            'label': 'Theta',
            'value': self.parameters['theta'],
            'type': 'float',
        }
        content['split'] = {
            'desc': 'Pre-solve the affine part (matrix inversion).',
            'label': 'Pre-solve',
            'value': self.parameters['split'],
            'type': 'bool',
        }

        tooltip = 'Method parameters'

        self.parametersWidget = ParametersWidget('', content, tooltip)

        # ---------------------------------------------------------------------
        # set Layout
        vbox = QVBoxLayout(self)
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.addWidget(self.titleWidget)
        vbox.addLayout(dimsLayout)
        vbox.addWidget(self.parametersWidget)
        self.setLayout(vbox)
        self.setContentsMargins(0, 0, 0, 0)

        # ---------------------------------------------------------------------
        # signals
        self.coreWidget.statusSig.sig.connect(self._status_changed)
        self.parametersWidget.modifiedSig.sig.connect(self._update_parameters)
        self.titleWidget.labelSignal.sig.connect(self._update_label)
        self.coreWidget.initSig.sig.connect(self._netlist_init)

    def _netlist_init(self):
        label = self.coreWidget.label
        self._update_label(label)
        self.initSig.sig.emit()

    def _update_parameters(self):
        if not self.parameters == self.parametersWidget.parameters:
            self.parameters.update(self.parametersWidget.parameters)
            self._change_status(False)

    def _update(self):
        self.expliciteWidget.desc.setText(str(self.method.dims.l()))
        self.impliciteWidget.desc.setText(str(self.method.dims.nl()))

    def _status_changed(self, s=False):
        if not s:
            self._change_status(s)

    def _change_status(self, s=False):
        self.titleWidget._change_status(s)
        self.statusSig.sig.emit(s)

    def _update_label(self, label):
        if not self.label == label:
            self.titleWidget._change_label(label)

    def _change_label(self, label):
        self.titleWidget._change_label(label)
        self._update_label(label)

    def _writelatex(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        dialog = QFileDialog()
        filename = os.path.join(self.folder, self.label + '.tex')
        dialog.selectFile(filename)
        fileName, _ = dialog.getSaveFileName(
            self,
            "Save LaTeX file as...",
            filename,
            "All Files (*);;Latex Files (*.tex)",
            "Latex Files (*.tex)",
            options=options)
        if not fileName == '':
            content = netlist2tex(
                self.coreWidget.graphWidget.netlistWidget.netlist)
            content += graphplot2tex(self.coreWidget.graphWidget.graph)
            content += core2tex(self.core)
            title = self.core.label
            texdocument(content, fileName, title)

    def _build(self):
        if not self.coreWidget.status:
            self.coreWidget._build()

        if self.coreWidget.status:
            #            try:
            self.method = self.core.to_method(self.parameters)

            self.method.label = self.label

            self._update()

            self._change_status(True)