Beispiel #1
0
class Cart_Pay(QWidget):

    #Initialiaze the first page for class View_Menu_First_Page()
    def __init__(self,parent=None):
        super(Cart_Pay,self).__init__(parent)
        self.resize(800,600)
        self.stackedwidget = QStackedWidget(self)
        self.stackedwidget.setGeometry(QtCore.QRect(0,0 , 800, 600))
        self.stackedwidget.setObjectName("stackwidget")

        self.add_first_page()

    #function to show first page
    def add_first_page(self):
        self.first_page = Pay_First_Page()
        self.stackedwidget.addWidget(self.first_page)
        self.stackedwidget.setCurrentIndex(0)
        print(self.first_page.tableWidget.rowCount())
        self.first_page.BlueButton.clicked.connect(self.add_second_page) #only can use lambda: to make use of return value form functions

    #function to show second page
    def add_second_page(self):
        self.second_page = See_Waiting_Time()
        self.stackedwidget.addWidget(self.second_page)
        self.stackedwidget.setCurrentIndex(1)
Beispiel #2
0
class MyStack(QMainWindow):
    def __init__(self, parent=None):
        super(MyStack, self).__init__(parent)

        self.setWindowTitle('A staked Widget')
        self.setFixedSize(400, 400)

        self.init_ui()

    def init_ui(self):
        self.cbx = QComboBox(self)
        self.cbx.addItems(['Boton', 'Etiqueta'])
        self.cbx.setGeometry(20, 20, 360, 24)

        self.boton = Boton(self)
        self.et = Etiqueta(self)

        self.MyStack = QStackedWidget(self)
        self.MyStack.addWidget(self.boton)
        self.MyStack.addWidget(self.et)

        self.MyStack.setGeometry(20, 84, 360, 250)

        self.cbx.activated.connect(self.do_something)

    def do_something(self):
        widget = self.cbx.currentIndex()
        self.MyStack.setCurrentIndex(widget)
Beispiel #3
0
class MoodMainActivity(QMainWindow):
    def __init__(self, widgets):
        super().__init__(None, Qt.MSWindowsFixedSizeDialogHint)
        self.stacker = QStackedWidget(self)
        self.stacker.setProperty('class', 'ctm-widget')
        self.widgets = [MoodActivity(self), MoodStackedActivity(widgets, self)]

        for w in self.widgets:
            self.stacker.addWidget(w)

        self.c_layout = QHBoxLayout()
        self.c_layout.addWidget(self.stacker)

        self.setLayout(self.c_layout)
        self.set_page(0)

    def show(self):
        super().show()
        self.move(screen_center(self))

    def set_page(self, i):
        self.setWindowTitle(self.widgets[i].windowTitle())
        self.stacker.setGeometry(self.widgets[i].geometry())
        self.setGeometry(self.widgets[i].geometry())
        self.stacker.setCurrentIndex(i)
        self.move(screen_center(self))
Beispiel #4
0
 def init_main_stacked_widget(self):
     """
     create and return the main stackedWidget object
     """
     stacked_widget = QStackedWidget(self)
     stacked_widget.setObjectName(u"stacked_widget")
     stacked_widget.setGeometry(QRect(0, 0, WINDOW_HEIGHT, WINDOW_WIDTH))
     return stacked_widget
Beispiel #5
0
class Login(
        QMainWindow
):  # Окно логина. Если вход с этого ip уже осуществлён, то логин и пароль можно ввести любые
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        uic.loadUi('ui/login.ui', self)
        self.stack = QStackedWidget()  # Виджет для переключения между окнами
        self.stack.addWidget(self)
        self.stack.setWindowTitle("Barrelgram")
        self.stack.setCurrentWidget(self)
        self.requestThread = RequestThread()  # Поток для запросов
        self.main = Main(self.requestThread)
        self.stack.addWidget(self.main)
        self.stack.setGeometry(self.geometry())
        self.stack.show()
        self.requestThread.start()  # Запуск потока
        self.button_login.clicked.connect(self.login)

    #        self.login(raw=True) Планировалось сделать автоматический вход, но PyQt не хочет

    def login(
        self,
        raw=False
    ):  # Параметр row нужен был для автоматического входа, если с этого ip уже вошли
        # Но PyQt не успевал так быстро переключать виджеты
        if (self.login_input.text() == ""
                or self.password_input.text() == "") and not raw:
            return

        data = {
            "login": self.login_input.text(),
            "password": self.password_input.text()
        }

        response = requests.post("http://" + SERVER_ADDRESS,
                                 data=data,
                                 params={
                                     "app_client": True
                                 }).json()
        if response["verdict"] == "denied":
            if not raw:
                self.button_login.setText("Invalid data!")
            return
        else:
            if not raw:
                global SEND_GET_REQUESTS
                self.button_login.setText("Login")
                self.main.updateData(response, load_photo=True)
                self.stack.setCurrentWidget(
                    self.main)  # Переключение на основное окно
                SEND_GET_REQUESTS = True  # Включение запросов
Beispiel #6
0
class View_Menu(QWidget):

    #Initialiaze the first page for class View_Menu_First_Page()
    def __init__(self,parent=None):
        super(View_Menu,self).__init__(parent)
        self.resize(800,600)
        self.stackedwidget = QStackedWidget(self)
        self.stackedwidget.setGeometry(QtCore.QRect(0,0 , 800, 600))
        self.stackedwidget.setObjectName("stackwidget")
        self.add_first_page()

    #function to show first page
    def add_first_page(self):
        self.first_page = View_Menu_First_Page()
        self.stackedwidget.addWidget(self.first_page)
        self.stackedwidget.setCurrentIndex(0)
        self.first_page.label_malay.clicked.connect(lambda:self.add_second_page(self.first_page.MY_link_click())) #only can use lambda: to make use of return value form functions
        self.first_page.label_mcdonalds.clicked.connect(lambda:self.add_second_page(self.first_page.MC_link_click())) #only can use lambda: to make use of return value form functions
        self.first_page.label_kfc.clicked.connect(lambda:self.add_second_page(self.first_page.KFC_link_click())) #only can use lambda: to make use of return value form functions
        self.first_page.label_subway.clicked.connect(lambda:self.add_second_page(self.first_page.Subway_link_click())) #only can use lambda: to make use of return value form functions

    #function to show second page
    def add_second_page(self,store):
        self.second_page = View_Menu_Second_Page(store)
        self.stackedwidget.addWidget(self.second_page)
        self.stackedwidget.setCurrentIndex(1)
        if 'Subway' in self.second_page.Logo.text():
            print('Logo')
            self.second_page.BlueButton.clicked.connect(lambda:self.add_third_page(self.first_page.Subway_link_click(),self.second_page.SearchMenu()))
        elif 'Malay' in self.second_page.Logo.text():
            print('Malay logo')
            self.second_page.BlueButton.clicked.connect(lambda:self.add_third_page(self.first_page.MY_link_click(),self.second_page.SearchMenu()))
        elif 'Mcdonalds' in self.second_page.Logo.text():
            print('Mcdonalds Logo')
            self.second_page.BlueButton.clicked.connect(lambda:self.add_third_page(self.first_page.Mc_link_click(),self.second_page.SearchMenu()))
        elif 'KFC' in self.second_page.Logo.text():
            print('KFC Logo')
            self.second_page.BlueButton.clicked.connect(lambda:self.add_third_page(self.first_page.KFC_link_click(),self.second_page.SearchMenu()))
            
    #function to show third page
    def add_third_page(self,store,date_and_time):
        self.third_page = View_Menu_Third_Page(store,date_and_time)
        self.stackedwidget.addWidget(self.third_page)
        self.stackedwidget.setCurrentIndex(2)
        #kfcCombine.KFC_breakfast_window.BlueButton_2.clicked.connect(self.go_back)
        self.third_page.BlueButton_2.clicked.connect(self.go_back)

    def go_back(self):
        self.stackedwidget.setCurrentIndex(0)
        self.stackedwidget.removeWidget(self.second_page)
        self.stackedwidget.removeWidget(self.third_page)
    def layout_chooseInsertingPreferences(self):
        # Check box.
        self.checkBox1 = QCheckBox(
            "Kopírovat hodnoty 'závod' a 'čas' z posledního záznamu", self)
        # self.checkBox1.toggle() # This is a QCheckBox constructor.
        self.checkBox1.setChecked(False)
        self.checkBox1.stateChanged.connect(self.event_checkBox1)
        self.checkBox1.setGeometry(15, self.layout_yPosition, 1000, 22)
        self.layout_yPosition += 35

        self.checkBox2 = QCheckBox(
            "Ostřihnout desetinou část u času při přidání řádku, a nezobrazovat ji v tabulkách.",
            self)
        self.checkBox2.setChecked(False)
        self.checkBox2.stateChanged.connect(self.event_checkBox2)
        self.checkBox2.setGeometry(15, self.layout_yPosition, 1000, 22)
        self.layout_yPosition += 35

        # Radio buttons.
        qgroupbox1 = QGroupBox(
            "Volba hodnot, které zadávat pro identifikaci účastníka ")
        radioButtonsGroup1 = QVBoxLayout()

        self.radioButton0 = QRadioButton(
            "Zadávat pouze 'ID přiřazení účastníka - skupina'")
        # self.radioButton0.toggled.connect(self.event_radioButtonsGroup1)
        radioButtonsGroup1.addWidget(self.radioButton0)
        self.radioButton1 = QRadioButton(
            "Zadávat společně hodnoty 'závod' a 'startovní číslo'")
        radioButtonsGroup1.addWidget(self.radioButton1)
        self.radioButton1.setChecked(True)
        self.radioButton1.toggled.connect(self.event_radioButtonsGroup1)

        radioButtonsGroup1.addStretch()
        qgroupbox1.setLayout(radioButtonsGroup1)

        myStWi = QStackedWidget(self)
        # myStWi.setContentsMargins(10, 10, 10, 10)
        myStWi.addWidget(qgroupbox1)

        myStWi.setGeometry(15, self.layout_yPosition, 1085, 80)
        self.layout_yPosition += 90
Beispiel #8
0
class stackedWidget(QDialog):
    def __init__(self, parent=None):
        super(stackedWidget, self).__init__(parent)

        self.setWindowTitle(
            "Pila de widgets (QStackedWidget) por : ANDRES NIÑO")
        self.setWindowIcon(QIcon("icono.png"))
        self.setWindowFlags(Qt.WindowCloseButtonHint
                            | Qt.MSWindowsFixedSizeDialogHint)
        self.setFixedSize(400, 400)

        self.initUI()

    def initUI(self):

        # ======================= WIDGETS ==========================

        self.comboBox = QComboBox(self)
        self.comboBox.addItems(["Boton", "Etiqueta"])
        self.comboBox.setGeometry(20, 20, 360, 24)

        # Instancias
        self.boton = Boton(self)
        self.etiqueta = Etiqueta(self)

        self.stackedWidget = QStackedWidget(self)
        self.stackedWidget.addWidget(self.boton)
        self.stackedWidget.addWidget(self.etiqueta)
        self.stackedWidget.setGeometry(20, 84, 360, 25)

        # ==================== EVENTO QCOMBOBOX ====================

        self.comboBox.activated.connect(self.cambiarWidget)

# ======================= FUNCIONES ============================

    def cambiarWidget(self):
        # Obtener el índice del item seleccionado en el QComboBox
        widget = self.comboBox.currentIndex()

        # Indicar el widget a visualizar
        self.stackedWidget.setCurrentIndex(widget)
Beispiel #9
0
class AppSettings(QDialog):

    SettingsWidgets = []

    def __init__(self, conf, **kwargs):
        super().__init__(**kwargs)

        self.conf = conf
        self.setWindowTitle(translate('AppSettings', 'LiSP preferences'))

        self.setWindowModality(QtCore.Qt.ApplicationModal)
        self.setMaximumSize(635, 530)
        self.setMinimumSize(635, 530)
        self.resize(635, 530)

        self.listWidget = QListWidget(self)
        self.listWidget.setGeometry(QtCore.QRect(5, 10, 185, 470))

        self.sections = QStackedWidget(self)
        self.sections.setGeometry(QtCore.QRect(200, 10, 430, 470))

        for widget in self.SettingsWidgets:
            widget = widget(parent=self)
            widget.resize(430, 465)
            widget.load_settings(self.conf)

            self.listWidget.addItem(translate('SettingsPageName', widget.Name))
            self.sections.addWidget(widget)

        if self.SettingsWidgets:
            self.listWidget.setCurrentRow(0)

        self.listWidget.currentItemChanged.connect(self._change_page)

        self.dialogButtons = QDialogButtonBox(self)
        self.dialogButtons.setGeometry(10, 495, 615, 30)
        self.dialogButtons.setStandardButtons(QDialogButtonBox.Cancel
                                              | QDialogButtonBox.Ok)

        self.dialogButtons.rejected.connect(self.reject)
        self.dialogButtons.accepted.connect(self.accept)

    def get_configuraton(self):
        conf = {}

        for n in range(self.sections.count()):
            widget = self.sections.widget(n)
            newconf = widget.get_settings()
            deep_update(conf, newconf)

        return conf

    @classmethod
    def register_settings_widget(cls, widget):
        if widget not in cls.SettingsWidgets:
            cls.SettingsWidgets.append(widget)

    @classmethod
    def unregister_settings_widget(cls, widget):
        if widget in cls.SettingsWidgets:
            cls.SettingsWidgets.remove(widget)

    def _change_page(self, current, previous):
        if not current:
            current = previous

        self.sections.setCurrentIndex(self.listWidget.row(current))
class AppSettings(QDialog):

    SettingsWidgets = []

    def __init__(self, conf, **kwargs):
        super().__init__(**kwargs)

        self.conf = conf
        self.setWindowTitle('LiSP preferences')

        self.setWindowModality(QtCore.Qt.ApplicationModal)
        self.setMaximumSize(635, 530)
        self.setMinimumSize(635, 530)
        self.resize(635, 530)

        self.listWidget = QListWidget(self)
        self.listWidget.setGeometry(QtCore.QRect(5, 10, 185, 470))

        self.sections = QStackedWidget(self)
        self.sections.setGeometry(QtCore.QRect(200, 10, 430, 470))

        for widget in self.SettingsWidgets:
            widget = widget(QtCore.QSize(430, 465), self)
            widget.set_configuration(self.conf)

            self.listWidget.addItem(widget.NAME)
            self.sections.addWidget(widget)

        if len(self.SettingsWidgets) > 0:
            self.listWidget.setCurrentRow(0)

        self.listWidget.currentItemChanged.connect(self._change_page)

        self.dialogButtons = QDialogButtonBox(self)
        self.dialogButtons.setGeometry(10, 495, 615, 30)
        self.dialogButtons.setStandardButtons(QDialogButtonBox.Cancel |
                                              QDialogButtonBox.Ok)

        self.dialogButtons.rejected.connect(self.reject)
        self.dialogButtons.accepted.connect(self.accept)

    def get_configuraton(self):
        conf = {}

        for n in range(self.sections.count()):
            widget = self.sections.widget(n)
            newconf = widget.get_configuration()
            deep_update(conf, newconf)

        return conf

    @classmethod
    def register_settings_widget(cls, widget):
        if widget not in cls.SettingsWidgets:
            cls.SettingsWidgets.append(widget)

    @classmethod
    def unregister_settings_widget(cls, widget):
        if widget not in cls.SettingsWidgets:
            cls.SettingsWidgets.remove(widget)

    def _change_page(self, current, previous):
        if not current:
            current = previous

        self.sections.setCurrentIndex(self.listWidget.row(current))
Beispiel #11
0
class LoginForm(QWidget):
    binds = {"login": None, "register": None}
    def __init__(self):
        super().__init__()

        self.mainwidget = QMainWindow(self)
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)

        self.main_stackedWidget = QStackedWidget(self)
        self.main_stackedWidget.setGeometry(0,70,600,400)

        self.login_page = QWidget()
        self.main_stackedWidget.addWidget(self.login_page)

        self.register_page = QWidget()
        self.main_stackedWidget.addWidget(self.register_page)

        #main screen properties
        self.setFixedSize(600,400)
        self.setStyleSheet("background-color:rgb(35,35,35);")

        #functions
        self.center()
        self.login_screen()

        #main_code_label
        self.main_code_label = QLabel("Code" , self)
        self.main_code_label.setFont(QFont('Arial' , 30))
        self.main_code_label.setGeometry(205,0,150,60)
        self.main_code_label.setAlignment(Qt.AlignTop)
        self.main_code_label.setStyleSheet("color:red")

        #main_duel_label
        self.main_duel_label = QLabel("Duel" , self)
        self.main_duel_label.setFont(QFont('Firestarter' , 30))
        self.main_duel_label.setGeometry(300,0,150,60)
        self.main_duel_label.setAlignment(Qt.AlignTop)
        self.main_duel_label.setStyleSheet("color:orange")

        #######################################
        ##titlebar variables
        #######################################


        #closebox
        self.closebox = QPushButton("X" , self)
        self.closebox.setFlat(True)
        self.closebox.setGeometry(550,0,50,30)
        self.closebox.clicked.connect(self.closeboxEvent)
        self.closebox.setStyleSheet("background-color:red;color:white;")

        #minimizebox
        self.minimizebox = QPushButton("_" , self)
        self.minimizebox.setGeometry(500,0,50,30)
        self.minimizebox.setFlat(True)
        self.minimizebox.clicked.connect(self.minimizeboxEvent)
        self.minimizebox.setStyleSheet("background-color:gray;color:white;")

        self.oldPos = self.pos()
        
        # state: Logined?
        self.state = False
    # Get State: Logined?
    def get_state():
        return state
    #titlebar movement functions
    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def mousePressEvent(self, event):
        self.oldPos = event.globalPos()

    def mouseMoveEvent(self, event):
        delta = QPoint (event.globalPos() - self.oldPos)
        #print(delta)
        self.move(self.x() + delta.x(), self.y() + delta.y())
        self.oldPos = event.globalPos()

    #closebutton
    def closeboxEvent(self):
    	self.close()

    #minimizebutton
    def minimizeboxEvent(self):
    	self.showMinimized()

    
    #####################################
    ##server-side
    ####################################
    @classmethod
    def bind(cls,name):
        assert (name in cls.binds)

        def getFunc(func):
            cls.binds[name] = func
        return getFunc   

    #Login Database
    def loginDatabaseConn(self):
        if self.login_email_textbox.text() == "" or self.login_pass_textbox.text() == "":
            login_error_messagebox = QMessageBox()
            login_error_messagebox.setStyleSheet("background-color:dimgray;color:silver;")
            login_error_messagebox.setText("Please fill in all blanks")
            login_error_messagebox.setWindowTitle("Error")
            login_error_messagebox.setIcon(QMessageBox.Warning)
            login_error_messagebox.setWindowIcon(QIcon("Buttons/warning.png"))
            login_error_messagebox.exec_()
        else:
            email , passwd = self.login_email_textbox.text() , self.login_pass_textbox.text()
            command_result = self.binds["login"](email, passwd)
    
    #registerlabel
    def registerLabelClicked(self):
        #register_email_label
        self.register_email_label = QLabel("Email" , self.register_page)
        self.register_email_label.setGeometry(100,5,100,100)
        self.register_email_label.setFont(QFont('Arial',18))
        self.register_email_label.setStyleSheet('color:silver')
        self.register_email_label.setAlignment(Qt.AlignTop)

        #register_email_textbox
        self.register_email_text = QLineEdit(self.register_page)
        self.register_email_text.move(200,0)
        self.register_email_text.resize(300,30)
        self.register_email_text.setStyleSheet("border: 3px solid dimgray;border-style:outset;border-width:2px;border-radius:10px;color:silver")

        #uslabel
        self.register_username_label = QLabel("Username",self.register_page)
        self.register_username_label.setFont(QFont('Arial' , 18))
        self.register_username_label.setGeometry(55,50,120,85)
        self.register_username_label.setStyleSheet("color:#BFBFBF;")

        #register_username_textbox
        self.register_username_textbox = QLineEdit(self.register_page)
        self.register_username_textbox.move(200,75)
        self.register_username_textbox.resize(300,30)
        self.register_username_textbox.setStyleSheet("border: 3px solid dimgray;border-style:outset;border-width:2px;border-radius:10px;color:silver")

        #register_password_label
        self.register_password_label = QLabel("Password",self.register_page)
        self.register_password_label.setFont(QFont('Arial' , 18))
        self.register_password_label.setGeometry(55,125,120,85)
        self.register_password_label.setStyleSheet("color:#BFBFBF;")


        #login_pass_textbox
        self.register_pass_textbox = QLineEdit(self.register_page)
        self.register_pass_textbox.move(200,150)
        self.register_pass_textbox.resize(300,30)
        self.register_pass_textbox.setStyleSheet("border: 3px solid dimgray;border-style:outset;border-width:2px;border-radius:10px;color:silver")
        self.register_pass_textbox.setEchoMode(QLineEdit.Password)

        #confirm text box label
        self.confirm_label = QLabel("Confirm" , self.register_page)
        self.confirm_label.setFont(QFont('Arial' , 18))
        self.confirm_label.setGeometry(70,200,120,70)
        self.confirm_label.setStyleSheet("color:#BFBFBF")

        #register password textbox
        self.register_confirm_pass_textbox = QLineEdit(self.register_page)
        self.register_confirm_pass_textbox.move(200,218)
        self.register_confirm_pass_textbox.resize(300,30)
        self.register_confirm_pass_textbox.setStyleSheet("border: 3px solid dimgray;border-style:outset;border-width:2px;border-radius:10px;color:silver")
        self.register_confirm_pass_textbox.setEchoMode(QLineEdit.Password)

        #register button add variables to database
        self.registerbutton = QPushButton("Register" , self.register_page)
        self.registerbutton.setGeometry(250,265,100,30)
        self.registerbutton.setStyleSheet("background-color:silver;border-style:outset;border-width:2px;border-radius:15px;padding:6px;border-color:#264348;")
        self.registerbutton.clicked.connect(self.registerDB)

        #login linked button
        self.go_login_screen = QPushButton("L͟o͟g͟i͟n͟",self.register_page)
        self.go_login_screen.setGeometry(270,305,50,20)
        self.go_login_screen.setFlat(True)
        self.go_login_screen.clicked.connect(self.login_screen)
        self.go_login_screen.setFont(QFont('Arial' , 8))
        self.go_login_screen.setStyleSheet("background-color:gray;color:rgb(175,93,72)")


        self.main_stackedWidget.setCurrentIndex(1)#go to the register page
    
    def registerDB(self):
        if self.register_email_text.text() == "" or self.register_pass_textbox.text() == "" or self.confirm_textbox.text() == "" or self.register_username_textbox.text() == "":
            register_error_messagebox = QMessageBox()
            register_error_messagebox.setStyleSheet("background-color:dimgray;color:silver;")
            register_error_messagebox.setText("Please fill in all blanks")
            register_error_messagebox.setWindowTitle("Error")
            register_error_messagebox.setIcon(QMessageBox.Warning)
            register_error_messagebox.setWindowIcon(QIcon("Buttons/warning.png"))
            register_error_messagebox.exec_()
        elif self.login_pass_textbox1.text() != self.confirm_textbox.text():
            register_pass_error_messagebox = QMessageBox()
            register_pass_error_messagebox.setStyleSheet("background-color:dimgray;color:silver;")
            register_pass_error_messagebox.setText("Passwords do not match")
            register_pass_error_messagebox.setWindowTitle("Error")
            register_pass_error_messagebox.setIcon(QMessageBox.Warning)
            register_pass_error_messagebox.setWindowIcon(QIcon("Buttons/warning.png"))
            register_pass_error_messagebox.exec_()
        else:
            register_username_label, email, passwd = self.register_username_textbox.text() , self.register_email_text.text() , self.register_pass_textbox.text()
            command_result = self.binds["register"](register_username_label, email, passwd)
    def login_screen(self):
        #login email label
        self.login_email_label = QLabel("Email" , self.login_page)
        self.login_email_label.setFont(QFont('Arial' , 20))
        self.login_email_label.setGeometry(100,20,100,40)
        self.login_email_label.setStyleSheet("color:#BFBFBF;")

    
        # login email textbox
        self.login_email_textbox = QLineEdit(self.login_page)
        self.login_email_textbox.move(250,22)
        self.login_email_textbox.resize(300,30)
        self.login_email_textbox.setStyleSheet("border: 3px solid dimgray;border-style:outset;border-width:2px;border-radius:10px;color:silver")

        #login_pass_textbox
        self.login_pass_textbox = QLineEdit(self.login_page)
        self.login_pass_textbox.move(250,130)
        self.login_pass_textbox.resize(300,30)
        self.login_pass_textbox.setStyleSheet("border: 3px solid dimgray;border-style:outset;border-width:2px;border-radius:10px;color:silver")
        self.login_pass_textbox.setEchoMode(QLineEdit.Password)
        #login passwor label
        self.login_password_label = QLabel("Password",self.login_page)
        self.login_password_label.setFont(QFont('Arial' , 18))
        self.login_password_label.setGeometry(100,86,120,120)
        self.login_password_label.setStyleSheet("color:#BFBFBF;")

        #letsgo(login) button check informations
        self.letsgobutton = QPushButton("Lets Go" , self.login_page)
        self.letsgobutton.setGeometry(250,200,100,30)
        self.letsgobutton.setStyleSheet("background-color:silver;border-style:outset;border-width:2px;border-radius:15px;padding:6px;border-color:#264348;")
        self.letsgobutton.clicked.connect(self.loginDatabaseConn)


        #register linked label
        self.register_linked_label = QPushButton("R͟e͟g͟i͟s͟t͟e͟r͟",self.login_page)
        self.register_linked_label.setGeometry(270,255,50,20)
        self.register_linked_label.clicked.connect(self.registerLabelClicked)
        self.register_linked_label.setFlat(True)
        self.register_linked_label.setFont(QFont('Arial' , 8))
        self.register_linked_label.setStyleSheet("background-color:rgb(35,35,35);color:rgb(175,93,72)")

        self.main_stackedWidget.setCurrentIndex(0)#go to the login page
    def keyPressEvent(self, e):
        if e.key() == Qt.Key_E:
            self.stw.setCurrentIndex(0)


class ThreadClass(QThread):
    def __init__(self, callback, parent=None):
        super(ThreadClass, self).__init__(parent)
        self.point = 0
        self.callback = callback

    def run(self):
        while 1:
            data = s.recv(1024)
            msg = data.decode('utf-8')
            if msg == 'goal':
                self.callback()
                #self.point += 10
                #print(msg, self.point)


if __name__ == "__main__":
    q = QApplication(sys.argv)
    st = QStackedWidget()
    st.addWidget(InitScene(st))
    st.addWidget(PlayScene(st))
    st.addWidget(RankingScene(st))
    st.setGeometry(0, 0, 540, 960)
    st.show()
    sys.exit(q.exec_())
class UiMainWindow(QWidget):
    """Main UI window of the application.

	Attributes:
	----------
	window_width: int
		Width of the window
	window_height: int
		Height of the window
	button_width: int
		Width of buttons
	button_height: int
		Height of buttons
	dist: int
		Distance to the edge of Widgets(Window/Button/Label...)
	model_selected: bool
		Shows whether a model is selected or not
	"""
    window_height = 650
    window_width = 800
    button_width = 180
    button_height = 50
    dist = 30
    model_selected = False
    textbox_height = 25
    small_button_width = 100
    small_button_height = 30
    debug_height = 200
    debug_mode = False
    accepted_download = False
    current_city = ""

    def __init__(self, parent) -> None:
        super().__init__(parent)

        main_window.setObjectName("main_window")
        main_window.resize(self.window_width, self.window_height)
        self.centralwidget = QWidget(main_window)
        self.centralwidget.setObjectName("centralwidget")
        self.detector = Detection()

        self.Box_Stadt = QComboBox(self.centralwidget)
        self.Box_Stadt.setGeometry(
            QRect(self.dist, self.dist, self.button_width, self.button_height))
        self.Box_Stadt.setObjectName("Box_Stadt")
        self.Box_Stadt.activated.connect(self.on_dropdown_selected)
        # dynamic city updates
        supported_cities_updater = Thread(target=update_dropdown,
                                          daemon=True,
                                          args=(self.Box_Stadt, ))
        supported_cities_updater.start()

        self.Text_City = QLineEdit(self.centralwidget)
        self.Text_City.setGeometry(
            QRect(self.dist + self.dist + self.button_width, self.dist + 10,
                  self.button_width, self.textbox_height))
        self.Text_City.setObjectName("Text_City")
        self.Text_City.setToolTip(
            'Enter a city you wish to detect sights in that you cannot find in the dropdown on the left after updating.'
        )

        self.Button_City = QPushButton(self.centralwidget)
        self.Button_City.setGeometry(
            QRect(
                int(2.3 * self.dist) + self.button_width + self.button_width,
                self.dist + 8, self.small_button_width,
                self.small_button_height))
        self.Button_City.setObjectName("Button_City")
        self.Button_City.clicked.connect(self.request_city)

        self.Button_Detection = QPushButton(self.centralwidget)
        self.Button_Detection.setGeometry(
            QRect(
                self.window_width - (self.dist + self.button_width),
                self.window_height - (self.dist + self.button_height + 20),
                self.button_width,
                self.button_height,
            ))
        self.Button_Detection.setObjectName("Button_Detection")
        self.Button_Detection.clicked.connect(self.detect_sights)

        self.Button_Bild = QPushButton(self.centralwidget)
        self.Button_Bild.setGeometry(
            QRect(
                self.dist,
                self.window_height - (self.dist + self.button_height + 20),
                self.button_width,
                self.button_height,
            ))
        self.Button_Bild.setObjectName("Button_Bild")
        self.Button_Bild.clicked.connect(lambda: self.camera_viewfinder.hide())
        self.Button_Bild.clicked.connect(
            lambda: self.Box_Camera_selector.setCurrentIndex(0))
        self.Button_Bild.clicked.connect(
            lambda: self.stacked_widget.setCurrentIndex(0))
        self.Button_Bild.clicked.connect(lambda: self.Label_Bild.show())
        self.Button_Bild.clicked.connect(self.dragdrop)

        self.available_cameras = QCameraInfo.availableCameras()

        self.Box_Camera_selector = QComboBox(self.centralwidget)
        self.Box_Camera_selector.setGeometry(
            QRect(
                self.window_width - (self.dist + self.button_width),
                self.dist,
                self.button_width,
                self.button_height,
            ))
        self.Box_Camera_selector.setObjectName("Box_Camera_selector")
        self.Box_Camera_selector.addItem("")
        # self.Box_Camera_selector.addItems([camera.description() for camera in self.available_cameras])
        self.Box_Camera_selector.addItems([
            "Camera " + str(i) + ": " +
            str(self.available_cameras[i].description())
            for i in range(len(self.available_cameras))
        ])
        self.Box_Camera_selector.currentIndexChanged.connect(
            self.select_camera)

        self.stacked_widget = QStackedWidget(self.centralwidget)
        label_height = (self.window_height - self.dist - self.button_height -
                        self.dist) - (self.dist + self.button_height +
                                      self.dist)
        label_start_y = self.dist + self.button_height + self.dist
        self.stacked_widget.setGeometry(
            QRect(
                self.dist,
                label_start_y,
                self.window_width - (self.dist * 2),
                label_height,
            ))

        self.camera_viewfinder = QCameraViewfinder()

        self.Label_Bild = ImageLabel(self)
        self.Label_Bild.setGeometry(
            QRect(0, 0, self.window_width - (self.dist * 2), label_height))

        self.checkBoxImprove = QCheckBox(
            "Help improving SightScan's detection quality", self.centralwidget)
        self.checkBoxImprove.setObjectName(u"improvement")
        self.checkBoxImprove.setGeometry(QRect(self.dist, 5, 350, 20))
        self.checkBoxImprove.setChecked(False)
        self.checkBoxImprove.stateChanged.connect(self.set_improve_quality_var)

        self.checkBox = QCheckBox("Debug", self.centralwidget)
        self.checkBox.setObjectName(u"checkBox")
        self.checkBox.setGeometry(
            QRect(self.window_width - (self.dist + 50),
                  self.window_height - (self.dist + 20), 70, 20))
        self.checkBox.setChecked(False)
        self.checkBox.stateChanged.connect(self.debug_click)

        # Setup logging
        fn = "logs/" + datetime.now().strftime(
            '%d_%m_%Y__%H_%M_%S') + 'log.log'
        if not os.path.exists("logs"):
            os.mkdir("logs")
        f = '%(asctime)s :: %(levelname)s :: %(filename)s :: %(funcName)s :: %(lineno)d :: %(message)s'
        self.textDebug = QTextEditLogger(self.centralwidget)
        self.textDebug.setFormatter(logging.Formatter(f))
        logging.basicConfig(filename=fn, format=f, level=logging.DEBUG)
        logging.getLogger().addHandler(self.textDebug)

        # Log Text Box in GUI
        self.textDebug.widget.setObjectName(u"textEdit")
        self.textDebug.widget.setEnabled(False)
        self.textDebug.widget.setGeometry(
            QRect(self.dist, self.window_height,
                  self.window_width - 2 * self.dist,
                  self.debug_height - self.dist))
        size_policy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
        size_policy.setHorizontalStretch(0)
        size_policy.setVerticalStretch(0)
        size_policy.setHeightForWidth(
            self.textDebug.widget.sizePolicy().hasHeightForWidth())
        self.textDebug.widget.setSizePolicy(size_policy)
        self.textDebug.widget.setReadOnly(True)

        self.stacked_widget.addWidget(self.Label_Bild)
        self.stacked_widget.addWidget(self.camera_viewfinder)

        main_window.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(main_window)
        self.menubar.setGeometry(QRect(0, 0, 678, 21))
        self.menubar.setObjectName("menubar")
        main_window.setMenuBar(self.menubar)

        self.statusbar = QStatusBar(main_window)
        self.statusbar.setObjectName("statusbar")
        main_window.setStatusBar(self.statusbar)

        main_window.setWindowIcon(QIcon(logo_without_text))

        self.retranslateUi(main_window)
        QMetaObject.connectSlotsByName(main_window)

    def set_improve_quality_var(self):
        self.improve_checkbox_enabled = self.checkBoxImprove.isChecked()

    def retranslateUi(self, main_window: QMainWindow) -> None:
        """Set the text initially for all items.

		Parameters
		----------
		main_window: QMainWindow
		    The instance of the prepared application window
		"""
        _translate = QCoreApplication.translate
        main_window.setWindowTitle(_translate(WINDOW, "SightScan"))
        self.Box_Stadt.addItems(['Choose City'] + initialize_cities())
        self.Box_Camera_selector.setItemText(
            0, _translate(WINDOW, "Choose Webcam"))
        self.Button_Detection.setText(_translate(WINDOW, START))
        self.Button_Bild.setText(_translate(WINDOW, ENABLE))
        self.Button_City.setText(_translate(WINDOW, "Add City"))

    def on_dropdown_selected(self) -> None:
        """Shows a pop-up for confirming the download of the selected city."""
        city_pretty_print = self.Box_Stadt.currentText()
        city = self.Box_Stadt.currentText().replace(' ', '_').upper()

        if city != "CHOOSE_CITY":
            self.current_city = self.Box_Stadt.currentText()
            # if no connection to dos
            if get_supported_cities() == []:
                latest_version = "couldn't get the latest version"
                downloaded_version = "couldn't get the downloaded version"
                print('no connection to dos')

            # if connection to dos
            else:
                downloaded_version = -1  # initialization

                Path("weights").mkdir(mode=0o700, exist_ok=True)

                if not os.path.exists("weights/versions.txt"):
                    with open('weights/versions.txt',
                              'w'):  # creating a version file
                        pass

                with open("weights/versions.txt", "r") as file:
                    for line in file:
                        elements = line.split("=")
                        if elements[0].upper() == city:
                            downloaded_version = int(elements[1])
                            break

                latest_version = get_dwh_model_version(city)

                if downloaded_version == -1:
                    msg = QMessageBox()
                    msg.setWindowTitle("Download City")
                    msg.setWindowIcon(QIcon(logo_without_text))
                    msg.setText("Do you want to download " +
                                city_pretty_print + "?")
                    msg.setIcon(QMessageBox.Question)
                    msg.setStandardButtons(QMessageBox.Cancel | QMessageBox.Ok)
                    msg.setDefaultButton(QMessageBox.Ok)
                    msg.setInformativeText("When downloaded, sights of " +
                                           city_pretty_print +
                                           " can be detected.")
                    msg.buttonClicked.connect(self.handover_city)

                    msg.exec_()

                elif latest_version > downloaded_version:
                    update_msg = QMessageBox()
                    update_msg.setWindowTitle("Update available")
                    update_msg.setWindowIcon(QIcon(logo_without_text))
                    update_msg.setText(
                        "Do you want to download an update for " + city + "?")
                    update_msg.setIcon(QMessageBox.Question)
                    update_msg.setStandardButtons(QMessageBox.Cancel
                                                  | QMessageBox.Ok)
                    update_msg.setDefaultButton(QMessageBox.Ok)
                    update_msg.setInformativeText(
                        "Updated cities can detect sights faster and more accurately. If you choose not to download, the "
                        + "detection will still work.")
                    update_msg.buttonClicked.connect(self.handover_city)

                    update_msg.exec_()
            if self.accepted_download is True or latest_version == downloaded_version:
                self.accepted_download = False
                self.show_download_result()
            self.model_selected = True
        else:
            self.model_selected = False

    def handover_city(self, button) -> None:
        """Starts the download of the pre-trained model of the selected city.

		Parameters
		----------
		button:
			Pushed button inside the popup.
		"""

        if "OK" in button.text().upper():
            city = self.Box_Stadt.currentText().replace(' ', '_').upper()
            self.model_selected = True
            model = get_downloaded_model(city)
            if model is not None:
                with open("weights/" + city + ".pt", "wb+") as file:
                    file.write(model)
            self.accepted_download = True
        elif "CANCEL" in button.text().upper():
            self.Box_Stadt.setCurrentIndex(0)

    def detect_sights(self) -> None:
        """Starts detection for the dropped image or shown webcam video
		with the downloaded model and displays the results in the label."""
        city = self.Box_Stadt.currentText().replace(' ', '_').upper()
        print("Detection Status: " + str(self.detector.detection))

        if self.model_selected is False:
            self.show_missing_model_popup()
        else:
            # start drag&drop image detection
            if self.stacked_widget.currentIndex() == 0 and self.Button_Bild.text() == DISABLE and \
              self.Label_Bild.image != logo_with_text:
                print(f"Starting detection of {self.Label_Bild.image}")
                wipe_prediction_input_images(INPUT_PREDICTION_DIR)
                shutil.copy2(self.Label_Bild.image, INPUT_PREDICTION_DIR)
                self.detector.enable_detection()
                self.detector.detect(self,
                                     weights='weights/' + city + '.pt',
                                     debug=self.debug_mode)
            # stop video detection
            elif self.stacked_widget.currentIndex(
            ) == 0 and self.Button_Detection.text() == STOP:
                self.stop_video_detection()
                time.sleep(2)
                self.reactivate_cam()
            # if webcam activated
            elif self.stacked_widget.currentIndex() == 1:
                if self.Button_Detection.text() == START:
                    self.Button_Detection.setText(
                        QCoreApplication.translate(WINDOW, STOP))
                    self.Label_Bild.setStyleSheet("""
					""")
                    print("Video Detection Started")
                    self.prep_video_detection()
                    source = self.Box_Camera_selector.currentIndex()
                    self.detector.enable_detection()
                    self.detection_thread = Thread(target=self.detector.detect,
                                                   args=(self, ),
                                                   kwargs={
                                                       'weights':
                                                       'weights/' + city +
                                                       '.pt',
                                                       'source':
                                                       str(source - 1),
                                                       'image_size':
                                                       704,
                                                       'debug':
                                                       self.debug_mode
                                                   })
                    self.detection_thread.start()
            else:
                print("Drop a File or select a Webcam!")

    def show_missing_model_popup(self) -> None:
        # Show Pop Up to choose a city
        emsg = QMessageBox()
        emsg.setWindowTitle("No city chosen")
        emsg.setWindowIcon(QIcon(logo_without_text))
        emsg.setText(
            "You need to choose a city before the detection can start.")
        emsg.setIcon(QMessageBox.Warning)
        emsg.setStandardButtons(QMessageBox.Ok)
        emsg.setDefaultButton(QMessageBox.Ok)

        emsg.exec_()

    def show_download_result(self) -> None:
        # city_pretty_print = self.Box_Stadt.currentText()

        self.model_selected = True
        newest_vers_msg = QMessageBox()
        newest_vers_msg.setWindowTitle("Ready for Detection!")
        newest_vers_msg.setWindowIcon(QIcon(logo_without_text))
        newest_vers_msg.setText("You can start detecting sights in " +
                                self.current_city + "!")
        newest_vers_msg.setStandardButtons(QMessageBox.Ok)
        newest_vers_msg.setDefaultButton(QMessageBox.Ok)

        newest_vers_msg.exec_()

    def request_city(self) -> None:
        # Send entered city to dwh and show confirmation popup if the city name is known
        city_input = self.Text_City.text()
        city_request = city_input.upper()
        if len(filter_city(city_input)) == 1:
            send_city_request(city_request)

            cmsg = QMessageBox()
            cmsg.setWindowTitle("Request confirmed")
            cmsg.setWindowIcon(QIcon(logo_without_text))
            cmsg.setText("Your request to add support for " + city_input +
                         " has been sent to our backend.")
            cmsg.setStandardButtons(QMessageBox.Ok)
            cmsg.setDefaultButton(QMessageBox.Ok)
            cmsg.exec_()
        else:
            cmsg = QMessageBox()
            cmsg.setWindowTitle("Unknown city name")
            cmsg.setWindowIcon(QIcon(logo_without_text))
            cmsg.setText(
                "The typed city name is not known. Please check the spelling.")
            cmsg.setIcon(QMessageBox.Warning)
            cmsg.setStandardButtons(QMessageBox.Ok)
            cmsg.setDefaultButton(QMessageBox.Ok)
            cmsg.exec_()

    def dragdrop(self) -> None:
        """Enables / disables Drag&Drop of images."""
        if self.Button_Bild.text() == ENABLE:
            # stop video detection if active
            if self.Button_Detection.text() == STOP:
                self.Button_Detection.setText(
                    QCoreApplication.translate(WINDOW, START))
                self.detector.disable_detection()
            self.Label_Bild.setAcceptDrops(True)
            self.Label_Bild.setText("\n\n Drop Image here \n\n")
            self.Label_Bild.setStyleSheet("""
				QLabel{
					border: 4px dashed #aaa
				}
			""")
            self.Button_Bild.setText(
                QCoreApplication.translate(WINDOW, DISABLE))
        elif self.Button_Bild.text() == DISABLE:
            self.Label_Bild.setAcceptDrops(False)
            self.Label_Bild.setText("")
            self.Label_Bild.setStyleSheet("")
            self.Label_Bild.image = logo_with_text
            self.Label_Bild.setPixmap(QPixmap(self.Label_Bild.image))
            self.Button_Bild.setText(QCoreApplication.translate(
                WINDOW, ENABLE))

    def select_camera(self, i):
        """Starts the selected camera. If "Choose webcam" is selected, it stops the camera.

		Parameters
		----------
		i:
			Index of the chosen camera.
		"""
        self.Label_Bild.image = logo_with_text
        self.Label_Bild.setPixmap(QPixmap(self.Label_Bild.image))
        if i == 0:
            self.camera.stop()
            self.detector.disable_detection()
            self.Button_Detection.setText(
                QCoreApplication.translate(WINDOW, START))
            self.stacked_widget.setCurrentIndex(0)
            self.camera_viewfinder.hide()
            self.Label_Bild.show()
            time.sleep(2)
            self.Label_Bild.image = logo_with_text
            self.Label_Bild.setPixmap(QPixmap(self.Label_Bild.image))
            self.Label_Bild.setStyleSheet("""
			""")
        else:
            self.camera_viewfinder.show()
            self.stacked_widget.setCurrentIndex(1)
            self.Label_Bild.hide()
            self.camera = QCamera(self.available_cameras[i - 1])
            self.camera.setViewfinder(self.camera_viewfinder)
            self.camera.error.connect(
                lambda: self.alert(self.camera.errorString()))
            self.camera.start()
            self.Button_Bild.setText(QCoreApplication.translate(
                WINDOW, ENABLE))

    def prep_video_detection(self) -> None:
        self.camera.stop()
        self.camera_viewfinder.hide()
        self.stacked_widget.setCurrentIndex(0)
        self.Label_Bild.image = loading_image
        self.Label_Bild.setPixmap(QPixmap(self.Label_Bild.image))
        self.Label_Bild.show()

    def stop_video_detection(self) -> None:
        self.Button_Detection.setText(QCoreApplication.translate(
            WINDOW, START))
        self.detector.disable_detection()
        self.stacked_widget.setCurrentIndex(1)
        self.Label_Bild.hide()
        self.camera_viewfinder.show()

    def debug_click(self, state):
        self.debug_mode = bool(state)

        if state:
            main_window.resize(self.window_width,
                               self.window_height + self.debug_height)
            self.textDebug.widget.setEnabled(True)
        else:
            main_window.resize(self.window_width, self.window_height)
            self.textDebug.widget.setEnabled(False)

    def reactivate_cam(self) -> None:
        self.Label_Bild.image = logo_with_text
        self.Label_Bild.setPixmap(QPixmap(self.Label_Bild.image))
        self.camera.start()

    def close_all(self) -> None:
        if self.Button_Detection.text() == STOP:
            self.detector.disable_detection()
            self.stop_video_detection()
class PyStream(QMainWindow):
    receive_signal = pyqtSignal(Metric)

    def __init__(self, rootPath):
        super().__init__()
        self.rootPath = rootPath
        self.__server = WebSocketServer(self)
        self.__server.start()
        self.__relay = PyRelay()
        self.__temp = PyTemp()
        self.__temp
        self.__temp.start()
        self.__stats_tab_index = 0
        self.__buttons_tab_index = 1
        self.enable_gui_switch = True
        self.timer = QTimer()
        self.timer.timeout.connect(self.__timer_tick)

        try:
            self.backlight = Backlight()
        except:
            self.fakeBacklightSysfs = FakeBacklightSysfs()
            self.fakeBacklightSysfs.__enter__()
            self.backlight = Backlight(
                backlight_sysfs_path=self.fakeBacklightSysfs.path)

        self.initUI()
        self.enable_screensaver()

    def initUI(self):
        logging.info("[GUI] Init main frame")
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
        self.setGeometry(0, 0, 800, 480)
        self.setWindowTitle("MediaDisplay-Server")
        self.setWindowIcon(QIcon("pystream/resource/pyalarm.png"))

        self.is_updating = False

        self.stack = QStackedWidget(self)
        self.stack.setGeometry(0, 0, 800, 480)
        self.panel_1 = QWidget()
        #self.panel_2 = QWidget()
        self.panel_3 = QWidget()
        self.stack.addWidget(self.panel_1)
        #self.stack.addWidget(self.panel_2)
        self.stack.addWidget(self.panel_3)

        #####################
        ##### Panel 1
        background_1 = QLabel(self.panel_1)
        background_1.setGeometry(0, 0, 800, 480)
        background_1.setStyleSheet(
            "background-image: url(pystream/resource/page_1.jpg);")

        self.gauge_cpu_1 = self.__create_gauge(self.panel_1, 95, 67)
        self.gauge_cpu_2 = self.__create_gauge(self.panel_1, 335, 67)
        self.gauge_cpu_3 = self.__create_gauge(self.panel_1, 580, 67)
        self.gauge_cpu_4 = self.__create_gauge(self.panel_1, 95, 230)
        self.gauge_cpu_5 = self.__create_gauge(self.panel_1, 335, 230)
        self.gauge_cpu_6 = self.__create_gauge(self.panel_1, 580, 230)

        self.label_cpu_1 = self.__create_label(self.panel_1,
                                               135,
                                               164,
                                               text="-- °C")
        self.label_cpu_2 = self.__create_label(self.panel_1,
                                               380,
                                               164,
                                               text="-- °C")
        self.label_cpu_3 = self.__create_label(self.panel_1,
                                               620,
                                               164,
                                               text="-- °C")
        self.label_cpu_4 = self.__create_label(self.panel_1,
                                               135,
                                               333,
                                               text="-- °C")
        self.label_cpu_5 = self.__create_label(self.panel_1,
                                               380,
                                               333,
                                               text="-- °C")
        self.label_cpu_6 = self.__create_label(self.panel_1,
                                               620,
                                               333,
                                               text="-- °C")

        self.__create_label(self.panel_1,
                            35,
                            384,
                            text="GPU",
                            font_size=20,
                            color="#FFFFFF")
        self.label_gpu_temp = self.__create_label(self.panel_1,
                                                  37,
                                                  419,
                                                  text="--°C",
                                                  font_size=15,
                                                  color="#FFFFFF")
        self.progress_gpu_load = self.__create_progressbar(
            self.panel_1, 95, 390, 174, 20)
        self.progress_gpu_mem_load = self.__create_progressbar(
            self.panel_1, 95, 420, 174, 20)

        self.__create_label(self.panel_1,
                            330,
                            395,
                            text="Down",
                            font_size=15,
                            color="#FFFFFF")
        self.__create_label(self.panel_1,
                            330,
                            419,
                            text="Up",
                            font_size=15,
                            color="#FFFFFF")
        self.label_net_down = self.__create_label(self.panel_1,
                                                  430,
                                                  395,
                                                  width=100,
                                                  height=25,
                                                  text="0",
                                                  font_size=15,
                                                  color="#FFFFFF")
        self.label_net_down.setAlignment(Qt.AlignRight)
        self.label_net_up = self.__create_label(self.panel_1,
                                                430,
                                                419,
                                                width=100,
                                                height=25,
                                                text="0",
                                                font_size=15,
                                                color="#FFFFFF")
        self.label_net_up.setAlignment(Qt.AlignRight)

        self.__create_label(self.panel_1,
                            546,
                            379,
                            text="Memory",
                            font_size=18,
                            color="#FFFFFF")
        self.progress_mem_load = self.__create_progressbar(
            self.panel_1, 551, 407, 203, 34)

        self.__create_button(self.panel_1, 774, 227, 26, 26, "arrow_right.png",
                             lambda: self.__change_page("Forward"))

        #####################
        ##### Panel 3
        background_3 = QLabel(self.panel_3)
        background_3.setGeometry(0, 0, 800, 480)
        background_3.setStyleSheet(
            "background-image: url(pystream/resource/page_2.jpg);")

        self.__create_button(self.panel_3,
                             125,
                             180,
                             100,
                             120,
                             "desk_lamp.png",
                             lambda: self.__relay.toggle_relay(PyRelay.BIG_2),
                             checkable=True)
        self.__create_button(
            self.panel_3,
            350,
            180,
            100,
            120,
            "keyboard.png",
            press=lambda: self.__relay.activate_relay(PyRelay.SMALL_1),
            release=lambda: self.__relay.deactivate_relay(PyRelay.SMALL_1))
        self.__create_button(self.panel_3,
                             575,
                             180,
                             100,
                             120,
                             "laptop.png",
                             lambda: self.__relay.toggle_relay(PyRelay.BIG_1),
                             checkable=True)

        self.__create_button(self.panel_3, 0, 227, 26, 26, "arrow_left.png",
                             lambda: self.__change_page("Backward"))

        self.label_room_temp = self.__create_label(self,
                                                   110,
                                                   0,
                                                   text="--°C",
                                                   color="#FFFFFF")
        self.label_time = self.__create_label(self,
                                              590,
                                              0,
                                              text="00:00",
                                              font_size=15,
                                              color="#FFFFFF")

        self.restore_gui()
        self.setCursor(QtCore.Qt.BlankCursor)
        logging.info("[GUI] Init done")
        self.timer.start(1000)
        self.receive_signal.connect(self.receive_gui)
        self.show()

    def __create_gauge(self, parent, x, y):
        gauge = AnalogGaugeWidget(parent)
        gauge.set_enable_fine_scaled_marker(False)
        gauge.set_enable_big_scaled_grid(False)
        gauge.set_enable_ScaleText(False)
        gauge.set_enable_CenterPoint(False)
        gauge.set_enable_Needle_Polygon(False)
        gauge.set_enable_barGraph(False)
        gauge.set_start_scale_angle(165)
        gauge.set_total_scale_angle_size(210)
        gauge.set_gauge_color_inner_radius_factor(600)
        gauge.set_MaxValue(100)
        gauge.setGeometry(x, y, 130, 130)
        gauge.update_value(50)
        gauge.set_DisplayValueColor(0, 255, 255)
        return gauge

    def __create_label(self,
                       parent,
                       x,
                       y,
                       width=None,
                       height=None,
                       text="",
                       font_size=15,
                       color="#00FFFF"):
        label = QLabel(parent)
        label.setText(text)
        font = QFont("Decorative", font_size)
        font.setBold(True)
        label.setFont(font)
        label.setStyleSheet("color: %s;" % color)
        if width is None or height is None:
            label.move(x, y)
        else:
            label.setGeometry(x, y, width, height)
        return label

    def __create_progressbar(self, parent, x, y, width, height):
        progress = GradiantProgressBar(parent)
        progress.setFormat("")
        progress.setValue(50)
        progress.setMaximum(100)
        progress.setGeometry(x, y, width, height)
        return progress

    def __create_button(self,
                        parent,
                        x,
                        y,
                        width,
                        height,
                        image,
                        click=None,
                        press=None,
                        release=None,
                        checkable=False):
        button = QPushButton(parent)
        button.setCheckable(checkable)
        if checkable:
            pressed_image = image.replace(".", "_pressed.")
            stre = "QPushButton {border-image: url(pystream/resource/" + image + ");} " \
                 + "QPushButton:checked {border-image: url(pystream/resource/" + pressed_image + ");}"
            button.setStyleSheet(stre)
        else:
            button.setStyleSheet("border-image: url(pystream/resource/" +
                                 image + ");")

        if click is not None:
            button.clicked.connect(click)
        if press is not None:
            button.pressed.connect(press)
        if release is not None:
            button.released.connect(release)

        button.setGeometry(x, y, width, height)
        button.setFlat(True)
        return button

    def __timer_tick(self):
        time = QDateTime.currentDateTime()
        timeDisplay = time.toString('hh:mm')
        temp = self.__temp.temperature

        self.label_time.setText(timeDisplay)
        self.label_room_temp.setText("%1.0f°C" % temp)

    def __change_page(self, direction):
        self.enable_gui_switch = False
        if direction == "Forward":
            if self.stack.currentIndex() < self.stack.count() - 1:
                self.stack.setCurrentIndex(self.stack.currentIndex() + 1)
        elif direction == "Backward":
            if self.stack.currentIndex() > 0:
                self.stack.setCurrentIndex(self.stack.currentIndex() - 1)

    def __send_key(self, key):
        msgObj = EventMessage(Action.Click, key)
        msg = json.dumps(msgObj.__dict__)
        self.__server.broadcast(msg)

    def udpate_gui(self, data: Metric):
        self.gauge_cpu_1.update_value(data.cpus[0].load)
        self.label_cpu_1.setText("%1.0f°C" % data.cpus[0].temperature)
        self.gauge_cpu_2.update_value(data.cpus[1].load)
        self.label_cpu_2.setText("%1.0f°C" % data.cpus[1].temperature)
        self.gauge_cpu_3.update_value(data.cpus[2].load)
        self.label_cpu_3.setText("%1.0f°C" % data.cpus[2].temperature)
        self.gauge_cpu_4.update_value(data.cpus[3].load)
        self.label_cpu_4.setText("%1.0f°C" % data.cpus[3].temperature)
        self.gauge_cpu_5.update_value(data.cpus[4].load)
        self.label_cpu_5.setText("%1.0f°C" % data.cpus[4].temperature)
        self.gauge_cpu_6.update_value(data.cpus[5].load)
        self.label_cpu_6.setText("%1.0f°C" % data.cpus[5].temperature)

        self.progress_mem_load.setValue(data.memory_load)

        self.label_gpu_temp.setText("%1.0f°C" % data.gpu.temperature)
        self.progress_gpu_load.setValue(data.gpu.load)
        self.progress_gpu_mem_load.setValue(data.gpu.memory_load)

        self.label_net_down.setText(data.network.down)
        self.label_net_up.setText(data.network.up)

    def receive_gui(self, data: Metric):
        if data.reset is not None and data.reset:
            logging.info("[GUI] Restoring initial image")
            self.restore_gui()
            self.enable_screensaver()
        else:
            if self.is_updating == False:
                self.is_updating = True
                try:
                    self.udpate_gui(data)
                    self.enable_gui()
                except Exception as e:
                    print(e)
                finally:
                    self.is_updating = False
            else:
                print("Gui is locked")
            self.disable_screensaver()

    def receive(self, data: Metric):
        if data is None:
            data = Metric(reset=True)
        self.receive_signal.emit(data)

        if data.send_display_brightness == True:
            msgObj = EventMessage(Action.Brightness, self.backlight.brightness)
            msg = json.dumps(msgObj.__dict__)
            self.__server.broadcast(msg)
        if data.display_brightness is not None and data.display_brightness >= 0 and data.display_brightness <= 100:
            self.backlight.brightness = data.display_brightness

    def enable_gui(self):
        if self.enable_gui_switch == True and self.stack.currentIndex(
        ) == self.__buttons_tab_index:
            self.stack.setCurrentIndex(self.__stats_tab_index)

    def restore_gui(self):
        self.enable_gui_switch = True

        self.stack.setCurrentIndex(2)
        self.label_cpu_1.setText("-- °C")
        self.label_cpu_2.setText("-- °C")
        self.label_cpu_3.setText("-- °C")
        self.label_cpu_4.setText("-- °C")
        self.label_cpu_5.setText("-- °C")
        self.label_cpu_6.setText("-- °C")

        self.gauge_cpu_1.update_value(50)
        self.gauge_cpu_2.update_value(50)
        self.gauge_cpu_3.update_value(50)
        self.gauge_cpu_4.update_value(50)
        self.gauge_cpu_5.update_value(50)
        self.gauge_cpu_6.update_value(50)

        self.progress_mem_load.setValue(50)

        self.label_gpu_temp.setText("%1.0f°C" % 0)
        self.progress_gpu_load.setValue(50)
        self.progress_gpu_mem_load.setValue(50)

        self.label_net_down.setText("0")
        self.label_net_up.setText("0")

        self.stack.setCurrentIndex(self.__buttons_tab_index)

    def update_app(self):
        GitUpdater.update(self.rootPath)

    def disable_screensaver(self):
        # disp = display.Display()
        # disp.set_screen_saver(0, 0, X.DontPreferBlanking, X.AllowExposures)
        # disp.sync()
        pyautogui.moveRel(0, 10)

    def enable_screensaver(self):
        disp = display.Display()
        screensaver = disp.get_screen_saver()
        if screensaver.timeout != 60:
            disp.set_screen_saver(60, 60, X.DefaultBlanking, X.AllowExposures)
            disp.sync()
Beispiel #15
0
graph_yield_view = GraphYieldView()
graph_yield_scroll_view = ScrollView(graph_yield_view, 3)
graph_yield_scroll_view.stacked_widgets = qStackedWidget
qStackedWidget.addWidget(graph_yield_scroll_view)

plan_crop_rotation = PlanCropRotationView()
plan_crop_rotation_scroll_view = ScrollView(plan_crop_rotation, 4)
plan_crop_rotation_scroll_view.stacked_widgets = qStackedWidget
qStackedWidget.addWidget(plan_crop_rotation_scroll_view)

treaty = TreatyView()
treaty_scroll_view = ScrollView(treaty, 5)
treaty_scroll_view.stacked_widgets = qStackedWidget
qStackedWidget.addWidget(treaty_scroll_view)

rig = RigView()
rig_scroll_view = ScrollView(rig, 6)
rig_scroll_view.stacked_widgets = qStackedWidget
qStackedWidget.addWidget(rig_scroll_view)

qStackedWidget.setGeometry(0, 0, 1200, 800)
qStackedWidget.setWindowTitle("Магазин")

loginView = LoginView()
loginView.stacked_widgets = qStackedWidget
loginView.setWindowTitle("Вход")
loginView.show()

sys.exit(app.exec_())
Beispiel #16
0
class Ui_Form(object):
    def setupUi(self, Form):
        self.form = Form
        self.O_answer = {}
        self.A_answer = {}
        self.file_list = os.listdir("Images")
        with open("count") as f:
            self.num = int(f.read())
        self.add_a = True
        self.add_o = False
        self.A_extra = {}
        self.O_extra = {}
        f = open('Attribute', encoding='utf-8-sig')
        self.A_dict = {}
        for line in f.readlines():
            temp = line[:-1].split(':')
            self.A_dict[temp[0]] = temp[1].split(',')
        print(self.A_dict)
        f.close()
        f = open('Object', encoding='utf-8-sig')
        self.O_dict = {}
        for line in f.readlines():
            temp = line[:-1].split(':')
            self.O_dict[temp[0]] = temp[1].split(',')
        f.close()
        print(self.O_dict)
        Form.setObjectName("Form")
        Form.resize(1179, 803)
        self.label_16 = QtWidgets.QLabel(Form)
        self.label_16.setGeometry(QtCore.QRect(30, 40, 441, 331))
        pixmap = QPixmap("./Images/" + self.file_list[self.num])
        self.label_16.setPixmap(pixmap)
        self.label_16.setScaledContents(True)

        self.label_17 = QtWidgets.QLabel(Form)
        self.label_17.setGeometry(QtCore.QRect(610, 720, 111, 31))
        pixmap = QPixmap("logo_iair.png")
        self.label_17.setPixmap(pixmap)
        self.label_17.setScaledContents(True)

        self.label_18 = QtWidgets.QLabel(Form)
        self.label_18.setGeometry(QtCore.QRect(400, 720, 201, 31))
        pixmap = QPixmap("xjtu_logo.png")
        self.label_18.setPixmap(pixmap)
        self.label_18.setScaledContents(True)

        self.groupBox = QtWidgets.QGroupBox(Form)
        self.groupBox.setGeometry(QtCore.QRect(490, 10, 351, 411))
        font = QtGui.QFont()
        font.setPointSize(18)
        self.groupBox.setFont(font)
        self.groupBox.setObjectName("groupBox")

        self.A_comboBox_list = []
        self.A_label_list = []
        with open('QListWidgetQSS.qss', 'r') as f:  # 导入QListWidget的qss样式
            self.list_style = f.read()
        font = QtGui.QFont()
        font.setPointSize(10)
        self.left_widget = QListWidget(self.groupBox)  # 左侧选项列表
        self.left_widget.setGeometry(QtCore.QRect(40, 40, 181, 360))
        self.left_widget.setStyleSheet(self.list_style)
        self.right_widget = QStackedWidget(self.groupBox)
        self.right_widget.setGeometry(QtCore.QRect(190, 40, 181, 360))

        with open('oQListWigetQSS.qss', 'r') as f:  # 导入QListWidget的qss样式
            self.olist_style = f.read()

        self.groupBox_5 = QtWidgets.QGroupBox(Form)
        self.groupBox_5.setGeometry(QtCore.QRect(850, 10, 291, 361))
        font = QtGui.QFont()
        font.setPointSize(10)
        self.oleft_widget = QListWidget(self.groupBox_5)  # 左侧选项列表
        self.oleft_widget.setGeometry(QtCore.QRect(10, 40, 181, 300))
        self.oleft_widget.setStyleSheet(self.olist_style)
        self.oright_widget = QStackedWidget(self.groupBox_5)
        self.oright_widget.setGeometry(QtCore.QRect(150, 40, 181, 300))

        font = QtGui.QFont()
        font.setPointSize(18)
        self.groupBox_5.setFont(font)
        self.groupBox_5.setAutoFillBackground(False)
        self.groupBox_5.setObjectName("groupBox_5")
        self.O_comboBox_list = []
        self.O_label_list = []
        self.pushButton = QtWidgets.QPushButton(Form)
        font = QtGui.QFont()
        font.setPointSize(18)
        self.pushButton.setFont(font)
        self.pushButton.setGeometry(QtCore.QRect(570, 630, 551, 61))
        self.pushButton.clicked.connect(self.btn_save)
        self.pushButton.setObjectName("pushButton")
        self.pushButton_2 = QtWidgets.QPushButton(Form)
        font = QtGui.QFont()
        font.setPointSize(18)
        self.pushButton_2.setFont(font)
        self.pushButton_2.setGeometry(QtCore.QRect(570, 560, 551, 61))
        self.pushButton_2.clicked.connect(self.btn_add_class)
        self.pushButton_2.setObjectName("pushButton_2")
        self.comboBox_11 = QtWidgets.QComboBox(Form)
        self.comboBox_11.setGeometry(QtCore.QRect(40, 440, 241, 31))
        font = QtGui.QFont()
        font.setPointSize(18)
        self.comboBox_11.setFont(font)
        self.comboBox_11.setEditable(False)
        self.comboBox_11.setObjectName("comboBox_11")
        for i, key in enumerate(self.A_dict.keys()):
            self.comboBox_11.addItem("")
        for i, key in enumerate(self.O_dict.keys()):
            self.comboBox_11.addItem("")
        self.lineEdit_2 = QtWidgets.QLineEdit(Form)
        self.lineEdit_2.setGeometry(QtCore.QRect(930, 480, 201, 21))
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.pushButton_3 = QtWidgets.QPushButton(Form)
        font = QtGui.QFont()
        font.setPointSize(18)
        self.pushButton_3.setFont(font)
        self.pushButton_3.setGeometry(QtCore.QRect(40, 530, 461, 61))
        self.pushButton_3.clicked.connect(self.btn_add_val)
        self.pushButton_3.setObjectName("pushButton_3")
        self.radioButton = QtWidgets.QRadioButton(Form)
        self.radioButton.setGeometry(QtCore.QRect(580, 480, 100, 20))
        self.radioButton.setChecked(True)
        self.radioButton.toggled.connect(self.radio_msg)
        self.radioButton.setObjectName("radioButton")
        self.radioButton_2 = QtWidgets.QRadioButton(Form)
        self.radioButton_2.setGeometry(QtCore.QRect(670, 480, 100, 20))
        self.radioButton_2.toggled.connect(self.radio_msg)
        self.radioButton_2.setObjectName("radioButton_2")
        self.textEdit = QtWidgets.QTextEdit(Form)
        self.textEdit.setGeometry(QtCore.QRect(300, 440, 201, 81))
        self.textEdit.setObjectName("textEdit")
        self.label_11 = QtWidgets.QLabel(Form)
        self.label_11.setGeometry(QtCore.QRect(40, 410, 60, 31))
        font = QtGui.QFont()
        font.setPointSize(18)
        self.label_11.setFont(font)
        self.label_11.setObjectName("label_11")
        self.label_12 = QtWidgets.QLabel(Form)
        self.label_12.setGeometry(QtCore.QRect(850, 480, 61, 21))
        font = QtGui.QFont()
        font.setPointSize(18)
        self.label_12.setFont(font)
        self.label_12.setObjectName("label_12")
        self.label_13 = QtWidgets.QLabel(Form)
        self.label_13.setGeometry(QtCore.QRect(300, 410, 141, 21))
        font = QtGui.QFont()
        font.setPointSize(18)
        self.label_13.setFont(font)
        self.label_13.setObjectName("label_13")
        self.label_9 = QtWidgets.QLabel(Form)
        self.label_9.setGeometry(QtCore.QRect(30, 380, 551, 31))
        font = QtGui.QFont()
        font.setPointSize(18)
        self.label_9.setFont(font)
        self.label_9.setObjectName("label_9")
        self.label_15 = QtWidgets.QLabel(Form)
        self.label_15.setGeometry(QtCore.QRect(860, 510, 71, 21))
        font = QtGui.QFont()
        font.setPointSize(18)
        self.label_15.setFont(font)
        self.label_15.setObjectName("label_15")
        self.lineEdit_3 = QtWidgets.QLineEdit(Form)
        self.lineEdit_3.setGeometry(QtCore.QRect(930, 510, 201, 21))
        self.lineEdit_3.setObjectName("lineEdit_3")
        self.checkBox = QtWidgets.QCheckBox(Form)
        self.checkBox.setGeometry(QtCore.QRect(580, 510, 87, 20))
        self.checkBox.setObjectName("checkBox")
        self.pushButton_4 = QtWidgets.QPushButton(Form)
        font = QtGui.QFont()
        font.setPointSize(18)
        self.pushButton_4.setFont(font)
        self.pushButton_4.setGeometry(QtCore.QRect(930, 380, 211, 41))
        self.pushButton_4.setObjectName("pushButton_4")
        self.pushButton_4.clicked.connect(self.btn4_back)
        self.pushButton_jump = QtWidgets.QPushButton(Form)
        self.pushButton_jump.setFont(font)
        self.pushButton_jump.setGeometry(QtCore.QRect(930, 430, 211, 41))
        self.pushButton_jump.setObjectName("pushButton_4")
        self.pushButton_jump.clicked.connect(self.btn_jump)
        self.QTextEdit = QtWidgets.QTextEdit(Form)
        self.QTextEdit.setGeometry(QtCore.QRect(40, 610, 461, 91))
        self.QTextEdit.setObjectName("QTextEdit")
        self.label_left = QtWidgets.QLabel(Form)
        self.label_left.setGeometry(QtCore.QRect(800, 700, 551, 31))
        font = QtGui.QFont()
        font.setPointSize(18)
        self.label_left.setFont(font)
        self.label_left.setObjectName("label_left")

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

    def retranslateUi(self, Form):
        '''加载界面ui'''

        self.left_widget.currentRowChanged.connect(
            self.right_widget.setCurrentIndex)  # list和右侧窗口的index对应绑定
        self.oleft_widget.currentRowChanged.connect(
            self.oright_widget.setCurrentIndex)  # list和右侧窗口的index对应绑定

        # self.left_widget.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)  # 隐藏滚动条
        self.left_widget.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

        for i, att_cl in enumerate(self.A_dict.keys()):
            self.item = QListWidgetItem(att_cl, self.left_widget)  # 左侧选项的添加
            font = QtGui.QFont()
            font.setPointSize(15)
            self.item.setFont(font)
            self.item.setSizeHint(QSize(15, 25))
            self.item.setTextAlignment(Qt.AlignCenter)  # 居中显示

            locals()['stack' + str(i)] = QListWidget()  # 左侧选项列表
            locals()['stack' + str(i)].setGeometry(QtCore.QRect(
                0, 0, 181, 360))
            locals()['stack' + str(i)].setStyleSheet(self.list_style)
            for att_v in self.A_dict[att_cl]:
                self.ritem = QListWidgetItem(att_v,
                                             locals()['stack' +
                                                      str(i)])  # 左侧选项的添加
                font = QtGui.QFont()
                font.setPointSize(15)
                self.ritem.setFont(font)
                self.ritem.setSizeHint(QSize(15, 25))
                self.ritem.setTextAlignment(Qt.AlignCenter)  # 居中显示
            self.right_widget.addWidget(locals()['stack' + str(i)])
            self.A_comboBox_list.append(locals()["stack" + str(i)])
            locals()['stack' + str(i)].currentRowChanged.connect(
                self.row_change)

        for i, obj_cl in enumerate(self.O_dict.keys()):
            self.oitem = QListWidgetItem(obj_cl, self.oleft_widget)  # 左侧选项的添加
            font = QtGui.QFont()
            font.setPointSize(15)
            self.oitem.setFont(font)
            self.oitem.setSizeHint(QSize(15, 25))
            self.oitem.setTextAlignment(Qt.AlignCenter)  # 居中显示

            locals()['ostack' + str(i)] = QListWidget()  # 左侧选项列表
            locals()['ostack' + str(i)].setGeometry(
                QtCore.QRect(0, 0, 181, 360))
            locals()['ostack' + str(i)].setStyleSheet(self.olist_style)
            for obj_v in self.O_dict[obj_cl]:
                self.oritem = QListWidgetItem(obj_v,
                                              locals()['ostack' +
                                                       str(i)])  # 左侧选项的添加
                font = QtGui.QFont()
                font.setPointSize(15)
                self.oritem.setFont(font)
                self.oritem.setSizeHint(QSize(15, 25))
                self.oritem.setTextAlignment(Qt.AlignCenter)  # 居中显示
            self.oright_widget.addWidget(locals()['ostack' + str(i)])
            self.O_comboBox_list.append(locals()["ostack" + str(i)])
            locals()['ostack' + str(i)].currentRowChanged.connect(
                self.orow_change)

        _translate = QtCore.QCoreApplication.translate
        for i, key in enumerate(self.A_dict.keys()):
            self.comboBox_11.setItemText(i, _translate("Form", key))
        for i, key in enumerate(self.O_dict.keys()):
            self.comboBox_11.setItemText(i + len(self.A_dict.keys()),
                                         _translate("Form", key))
        Form.setWindowTitle(_translate("Form", "Anotation Tool"))
        self.groupBox.setTitle(_translate("Form", "属性"))
        self.groupBox_5.setTitle(_translate("Form", "对象"))
        self.pushButton_3.setText(_translate("Form", "完成添加"))
        self.radioButton.setText(_translate("Form", "属性"))
        self.radioButton_2.setText(_translate("Form", "对象"))
        self.label_11.setText(_translate("Form", "名称:"))
        self.label_12.setText(_translate("Form", "名称:"))
        self.label_13.setText(_translate("Form", "值:"))
        self.label_9.setText(
            _translate("Form", "文件名称:" + self.file_list[self.num]))
        self.label_left.setText(
            _translate(
                "Form", "图片已标注:" + str(len(os.listdir("Labels/"))) + ",还剩:" +
                str(len(self.file_list) - len(os.listdir("Labels/")))))
        self.pushButton.setText(_translate("Form", "注释图片"))
        self.pushButton_2.setText(_translate("Form", "属性/对象完成添加"))
        self.label_15.setText(_translate("Form", "值:"))
        self.checkBox.setText(_translate("Form", "更新到图表"))
        self.pushButton_4.setText(_translate("Form", "上一张图片"))
        self.pushButton_jump.setText(_translate("Form", "跳过图片"))

    def btn_jump(self):
        self.num += 1
        with open("count", "w") as f:
            f.write(str(self.num))
        shutil.copy("./Images/" + self.file_list[self.num - 1],
                    "./SkipImages/")
        if self.num > len(self.file_list) - 1:
            sys.exit(0)
        pixmap = QPixmap("./Images/" + self.file_list[self.num])
        self.label_16.setPixmap(pixmap)
        self.label_16.setScaledContents(True)
        self.left_widget.reset()
        self.oleft_widget.reset()
        _translate = QtCore.QCoreApplication.translate
        self.label_9.setText(
            _translate("Form", "Image Name:" + self.file_list[self.num]))
        self.label_left.setText(
            _translate(
                "Form", "图片已标注:" + str(len(os.listdir("Labels/"))) + ",还剩:" +
                str(len(self.file_list) - len(os.listdir("Labels/")))))
        for comboBox_i in self.A_comboBox_list:
            comboBox_i.reset()
        for comboBox_i in self.O_comboBox_list:
            comboBox_i.reset()
        self.A_answer = {}
        self.O_answer = {}
        self.QTextEdit.clear()

    def row_change(self):
        cv = self.left_widget.currentIndex().data()
        i = self.left_widget.currentIndex().row()
        j = self.A_comboBox_list[i].currentIndex().row()
        vv = self.A_comboBox_list[i].currentIndex().data()
        self.A_answer[cv] = vv
        self.QTextEdit.setPlainText(
            str("对象:\n") + str(self.O_answer) + "\n" + str("属性:\n") +
            str(self.A_answer) + "\n")

    def orow_change(self):
        cv = self.oleft_widget.currentIndex().data()
        i = self.oleft_widget.currentIndex().row()
        j = self.O_comboBox_list[i].currentIndex().row()
        vv = self.O_comboBox_list[i].currentIndex().data()
        self.O_answer[cv] = vv
        self.QTextEdit.setPlainText(
            str("对象:\n") + str(self.O_answer) + "\n" + str("属性:\n") +
            str(self.A_answer) + "\n")

    def btn_save(self):
        self.num += 1
        with open("count", "w") as f:
            f.write(str(self.num))
        text = self.QTextEdit.toPlainText()
        O_an = eval(text.split('\n')[1])
        A_an = eval(text.split('\n')[3])
        if os.path.exists("./Labels/" + self.file_list[self.num - 1] +
                          ".json"):
            os.remove("./Labels/" + self.file_list[self.num - 1] + ".json")
        dic = {}
        dic['object'] = O_an
        A_an_list = []
        for att in A_an.keys():
            A_an_list.append({att: A_an[att]})
        dic['attributes'] = A_an_list
        with open("./Labels/" + self.file_list[self.num - 1] + ".json",
                  mode="a") as f:
            json.dump(dic, f, ensure_ascii=False)
        if self.num > len(self.file_list) - 1:
            sys.exit(0)
        pixmap = QPixmap("./Images/" + self.file_list[self.num])
        self.label_16.setPixmap(pixmap)
        self.label_16.setScaledContents(True)
        self.left_widget.reset()
        self.oleft_widget.reset()
        _translate = QtCore.QCoreApplication.translate
        self.label_9.setText(
            _translate("Form", "Image Name:" + self.file_list[self.num]))
        self.label_left.setText(
            _translate(
                "Form", "图片已标注:" + str(len(os.listdir("Labels/"))) + ",还剩:" +
                str(len(self.file_list) - len(os.listdir("Labels/")))))
        for comboBox_i in self.A_comboBox_list:
            comboBox_i.reset()
        for comboBox_i in self.O_comboBox_list:
            comboBox_i.reset()
        self.A_answer = {}
        self.O_answer = {}
        self.QTextEdit.clear()

    def btn_add_val(self):
        my_key = self.comboBox_11.currentText()
        text = self.textEdit.toPlainText()
        text_list = text.split(',')
        _translate = QtCore.QCoreApplication.translate
        for i, key in enumerate(self.A_dict.keys()):
            if key == my_key:
                lines = []
                with open("Attribute", encoding='utf-8-sig') as f:
                    for line in f.readlines():
                        temp = line[:-1].split(':')
                        if temp[0] == my_key:
                            lines.append(line[:-1] + ',' + text + '\n')
                        else:
                            lines.append(line)
                with open("Attribute", 'w', encoding='utf-8') as f:
                    s = ''.join(lines)
                    f.write(str(s))
                for txt in text_list:
                    self.item = QListWidgetItem(
                        txt, self.A_comboBox_list[i])  # 左侧选项的添加
                    font = QtGui.QFont()
                    font.setPointSize(15)
                    self.item.setFont(font)
                    self.item.setSizeHint(QSize(15, 25))
                    self.item.setTextAlignment(Qt.AlignCenter)  # 居中显示
                self.A_dict[key] += text_list
        for i, key in enumerate(self.O_dict.keys()):
            if key == my_key:
                lines = []
                with open("Object", encoding="utf-8-sig") as f:
                    for line in f.readlines():
                        temp = line[:-1].split(':')
                        if temp[0] == my_key:
                            lines.append(line[:-1] + ',' + text + '\n')
                        else:
                            lines.append(line)
                with open("Object", 'w', encoding='utf-8') as f:
                    s = ''.join(lines)
                    f.write(str(s))
                for txt in text_list:
                    self.oitem = QListWidgetItem(
                        txt, self.O_comboBox_list[i])  # 左侧选项的添加
                    font = QtGui.QFont()
                    font.setPointSize(15)
                    self.oitem.setFont(font)
                    self.oitem.setSizeHint(QSize(15, 25))
                    self.oitem.setTextAlignment(Qt.AlignCenter)  # 居中显示
                self.O_dict[key] += text_list
        print([my_key, text])

        self.textEdit.setText("")

    def radio_msg(self):
        if self.radioButton.isChecked():
            self.add_a = True
            self.add_o = False
        if self.radioButton_2.isChecked():
            self.add_o = True
            self.add_a = False

    def btn_add_class(self):
        if self.add_a:
            self.radioButton.setChecked(True)
            my_key = self.lineEdit_2.text()
            my_val = self.lineEdit_3.text()
            my_val = my_val.split(",")
            _translate = QtCore.QCoreApplication.translate
            if self.checkBox.isChecked():
                if len(my_key) != 0:
                    i = len(self.A_comboBox_list)
                    self.item = QListWidgetItem(my_key,
                                                self.left_widget)  # 左侧选项的添加
                    font = QtGui.QFont()
                    font.setPointSize(15)
                    self.item.setFont(font)
                    self.item.setSizeHint(QSize(15, 25))
                    self.item.setTextAlignment(Qt.AlignCenter)  # 居中显示

                    locals()['stack' + str(i)] = QListWidget()  # 左侧选项列表
                    locals()['stack' + str(i)].setGeometry(
                        QtCore.QRect(0, 0, 181, 360))
                    locals()['stack' + str(i)].setStyleSheet(self.list_style)
                    for att_v in my_val:
                        self.ritem = QListWidgetItem(
                            att_v,
                            locals()['stack' + str(i)])  # 左侧选项的添加
                        font = QtGui.QFont()
                        font.setPointSize(15)
                        self.ritem.setFont(font)
                        self.ritem.setSizeHint(QSize(15, 25))
                        self.ritem.setTextAlignment(Qt.AlignCenter)  # 居中显示
                    self.right_widget.addWidget(locals()['stack' + str(i)])
                    self.A_comboBox_list.append(locals()["stack" + str(i)])
                    locals()['stack' + str(i)].currentRowChanged.connect(
                        self.row_change)
                    self.A_dict[my_key] = my_val
                    lines = []
                    with open("Attribute", encoding="utf-8-sig") as f:
                        for line in f.readlines():
                            lines.append(line)
                        lines.append('\n' + my_key + ":" + ",".join(my_val))
                    with open("Attribute", 'w', encoding="utf-8") as f:
                        s = ''.join(lines)
                        f.write(str(s))
                    self.comboBox_11.addItem("")
                    self.comboBox_11.setItemText(
                        len(self.A_dict.keys()) + len(self.O_dict.keys()) - 1,
                        _translate("Form", my_key))
            else:
                text = self.QTextEdit.toPlainText()
                if len(text) != 0:
                    self.A_answer = eval(text.split('\n')[3])
                    self.O_answer = eval(text.split('\n')[1])
                else:
                    self.A_answer = {}
                    self.O_answer = {}
                # print(A_an)
                self.A_answer[my_key] = my_val[0]
                self.QTextEdit.setPlainText(
                    str("对象:\n") + str(self.O_answer) + "\n" + str("属性:\n") +
                    str(self.A_answer) + "\n")
        if self.add_o:
            self.add_o = False
            self.radioButton.setChecked(True)
            my_key = self.lineEdit_2.text()
            my_val = self.lineEdit_3.text()
            my_val = my_val.split(",")
            _translate = QtCore.QCoreApplication.translate
            if self.checkBox.isChecked():
                if len(my_key) != 0:
                    i = len(self.O_comboBox_list)
                    self.oitem = QListWidgetItem(my_key,
                                                 self.oleft_widget)  # 左侧选项的添加
                    font = QtGui.QFont()
                    font.setPointSize(15)
                    self.oitem.setFont(font)
                    self.oitem.setSizeHint(QSize(15, 25))
                    self.oitem.setSizeHint(QSize(15, 20))
                    self.oitem.setTextAlignment(Qt.AlignCenter)  # 居中显示

                    locals()['ostack' + str(i)] = QListWidget()  # 左侧选项列表
                    locals()['ostack' + str(i)].setGeometry(
                        QtCore.QRect(0, 0, 181, 360))
                    locals()['ostack' + str(i)].setStyleSheet(self.olist_style)
                    for obj_v in my_val:
                        self.oritem = QListWidgetItem(
                            obj_v,
                            locals()['ostack' + str(i)])  # 左侧选项的添加
                        font = QtGui.QFont()
                        font.setPointSize(15)
                        self.oritem.setFont(font)
                        self.oritem.setSizeHint(QSize(15, 25))
                        self.oritem.setTextAlignment(Qt.AlignCenter)  # 居中显示
                    self.oright_widget.addWidget(locals()['ostack' + str(i)])
                    self.O_comboBox_list.append(locals()["ostack" + str(i)])
                    locals()['ostack' + str(i)].currentRowChanged.connect(
                        self.orow_change)
                    self.O_dict[my_key] = my_val
                    lines = []
                    with open("Object", encoding="utf-8-sig") as f:
                        for line in f.readlines():
                            lines.append(line)
                        lines.append('\n' + my_key + ":" + ",".join(my_val))
                    with open("Object", 'w', encoding="utf-8") as f:
                        s = ''.join(lines)
                        f.write(str(s))
                    self.comboBox_11.addItem("")
                    self.comboBox_11.setItemText(
                        len(self.A_dict.keys()) + len(self.O_dict.keys()) - 1,
                        _translate("Form", my_key))
            else:
                text = self.QTextEdit.toPlainText()
                if len(text) != 0:
                    self.A_answer = eval(text.split('\n')[3])
                    self.O_answer = eval(text.split('\n')[1])
                else:
                    self.A_answer = {}
                    self.O_answer = {}
                self.O_answer[my_key] = my_val[0]
                self.QTextEdit.setPlainText(
                    str("对象:\n") + str(self.O_answer) + "\n" + str("属性:\n") +
                    str(self.A_answer) + "\n")
        self.radio_flag = False

        self.checkBox.setChecked(False)
        self.lineEdit_2.setText("")
        self.lineEdit_3.setText("")

    def btn4_back(self):
        if self.num < 1:
            sys.exit(0)
        self.num = self.num - 1
        with open("count", "w") as f:
            f.write(str(self.num))
        pixmap = QPixmap("./Images/" + self.file_list[self.num])
        self.label_16.setPixmap(pixmap)
        self.label_16.setScaledContents(True)
        _translate = QtCore.QCoreApplication.translate
        self.label_9.setText(
            _translate("Form", "Image Name:" + self.file_list[self.num]))
        for comboBox_i in self.A_comboBox_list:
            comboBox_i.reset()
        for comboBox_i in self.O_comboBox_list:
            comboBox_i.reset()
        self.QTextEdit.clear()
    label_energy.setFont(QFont("Ubuntu Mono", 15))
    label_energy.setGeometry(
        QtCore.QRect(left_margin + string_width + 30, 690, 1200, 200))

    stacked_widget_push_button_start_app = QPushButton('Start', main)
    stacked_widget_push_button_start_app.setGeometry(
        QtCore.QRect(left_margin, 0, 200, 40))
    stacked_widget_push_button_start_app.clicked.connect(on_click_start)

    stacked_widget_push_button_param = QPushButton('Parameters', main)
    stacked_widget_push_button_param.setGeometry(
        QtCore.QRect(left_margin + 200, 0, 200, 40))
    stacked_widget_push_button_param.clicked.connect(on_click_parameters)

    stacked_widget = QStackedWidget(main)
    stacked_widget.setGeometry(
        QtCore.QRect(0, 50, string_width + left_margin, main_height + 50))

    widget_start = QWidget()
    widget_parameters = QWidget()
    widget_plots = QWidget(main)
    widget_plots.setGeometry(QtCore.QRect(string_width + 100, 0, 1280, 900))
    widget_plots.setVisible(False)

    # -------------
    # WIDGET PLOTS
    l1 = QLabel(widget_plots)
    l1.setGeometry(QtCore.QRect(0, 0, 550, 450))
    px = QPixmap('tools/generation_size.png').scaled(550, 450)
    l1.setPixmap(px)

    l1 = QLabel(widget_plots)
Beispiel #18
0
class MinWindow(Winform):
    def __init__(self, parent=None):
        super(MinWindow, self).__init__(parent)

        self.setWindowTitle('主窗口')
        self.resize(900, 600)
        self.center()

        # 创建主窗口
        self.create_main_frame()
        self.add_button()
        # 创建菜单
        self.create_menu()
        # 画出图像
        self.on_draw()

        # 绑定所有事件
        self.events_all_siganl_connect()

    def save_plot(self):
        # 保存当前matplotlib图像
        file_choices = "PNG (*.png)|*.png"

        # path = QFileDialog.getSaveFileName(self,
        #                                    'Save file', '',
        #                                    file_choices)
        # path = self.get_current_path()
        self.stack_tabWidget.currentWidget().mpl_nav_toolbar.save_figure()

        # if path:
        #     print('保存啊')
        #     # self.stack_tabWidget.currentWidget()
        #     self.stack_tabWidget.currentWidget().mpl_nav_toolbar.save_figure()
        #     print('保存了啊')
        #     self.statusBar().showMessage('Saved to %s' % path, 2000)

        pass

    def create_menu(self):
        # 添加菜单栏

        self.setCentralWidget(self.centralwidget)

        # 添加菜单栏
        self.main_menubar = QtWidgets.QMenuBar()
        self.main_menubar.setGeometry(QtCore.QRect(0, 0, 800, 23))
        self.main_menubar.setObjectName("main_menubar")

        self.menu = QtWidgets.QMenu(self.main_menubar)
        self.menu.setObjectName("menu")
        self.file_menu = QtWidgets.QMenu(self.main_menubar)
        self.file_menu.setObjectName("file_menu")

        self.save_menu = QtWidgets.QMenu(self.main_menubar)
        self.save_menu.setObjectName("save_menu")

        self.setMenuBar(self.main_menubar)

        self.statusbar = QtWidgets.QStatusBar()
        self.statusbar.setObjectName("statusbar")

        self.setStatusBar(self.statusbar)

        # 添加状态栏
        self.show_status_bar()
        # self.statusbar.showMessage("这是状态栏")

        self.plot_save_action = QAction(self)
        self.plot_save_action.setObjectName("plot_save_action")

        _translate = QtCore.QCoreApplication.translate
        self.menu.setTitle(_translate("MainWindow", "菜单"))
        self.file_menu.setTitle(_translate("MainWindow", "保存"))
        self.save_menu.setTitle(_translate("MainWindow", "保存图片"))
        self.plot_save_action.setText(_translate("MainWindow", "保存图片"))

        self.file_menu.addAction(self.plot_save_action)
        self.main_menubar.addAction(self.menu.menuAction())
        self.main_menubar.addAction(self.file_menu.menuAction())
        self.main_menubar.addAction(self.save_menu.menuAction())

        self.retranslateUi()

        # 给菜单按钮添加绑定事件
        # QtCore.QMetaObject.connectSlotsByName(self)
        save_file_action = self.create_action("&保存图像",
                                              shortcut="Ctrl+S",
                                              slot=self.save_plot,
                                              tip="Save the plot")
        quit_action = self.create_action("&Quit",
                                         slot=self.close,
                                         shortcut="Ctrl+Q",
                                         tip="Close the application")

        self.add_actions(self.file_menu, (save_file_action, None, quit_action))
        pass

    def create_main_frame(self):
        # 窗口布局
        # 添加主窗口
        self.setObjectName("MainWindow")
        # self.layout =
        self.layout = QVBoxLayout(self)
        self.centralwidget = QtWidgets.QWidget()
        self.centralwidget.setObjectName("centralwidget")
        self.setCentralWidget(self.centralwidget)

        self.main_widget = QtWidgets.QWidget(self.centralwidget)
        self.main_widget.setGeometry(QtCore.QRect(10, 20, 761, 481))
        self.main_widget.setObjectName("main_widget")

        # 此区域存放图像
        self.stack_tabWidget = QtWidgets.QTabWidget(self.main_widget)
        self.stack_tabWidget.setGeometry(QtCore.QRect(30, 60, 721, 401))
        self.stack_tabWidget.setObjectName("stack_tabWidget")

        # 此区域存放图像的工具栏
        self.toolbar_stackedWidget = QStackedWidget(self.main_widget)
        self.toolbar_stackedWidget.setGeometry(QtCore.QRect(20, 0, 791, 71))
        self.toolbar_stackedWidget.setObjectName("toolbar_stackedWidget")
        self.layout.addWidget(self.centralwidget)

    def on_draw(self):
        # 添加图像
        self.draw_all_stack_tab()
        # 添加工具栏
        self.set_all_stack_tab_toolbar()
        pass

    def create_status_bar(self):

        pass

    def create_action(self,
                      text,
                      slot=None,
                      shortcut=None,
                      icon=None,
                      tip=None,
                      checkable=False,
                      signal="triggered()"):
        action = QAction(text, self)
        if icon is not None:
            # action.setIcon(QIcon(":/%s.png" % button_icon))
            pass
        if shortcut is not None:
            action.setShortcut(shortcut)
        if tip is not None:
            action.setToolTip(tip)
            action.setStatusTip(tip)
        if slot is not None:
            action.triggered.connect(slot)
        if checkable:
            action.setCheckable(True)
        return action

    def add_actions(self, target, actions):
        for action in actions:
            if action is None:
                target.addSeparator()
            else:
                target.addAction(action)

    def add_button(self):
        self.save_pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.save_pushButton.setGeometry(QtCore.QRect(800, 160, 75, 23))
        self.save_pushButton.setObjectName("save_pushButton")
        pass

    def on_about(self):
        # 弹出关于此软件的信息
        msg = """ A demo of using PyQt with matplotlib:

         * Use the matplotlib navigation bar
         * Add values to the text box and press Enter (or click "Draw")
         * Show or hide the grid
         * Drag the slider to modify the width of the bars
         * Save the plot to a file using the File menu
         * Click on a bar to receive an informative message
        """
        QMessageBox.about(self, "About the demo", msg.strip())

    def retranslateUi(self):
        # 设置各个菜单的名字
        _translate = QtCore.QCoreApplication.translate

        self.setWindowTitle(_translate("MainWindow", "曲线翻页"))

        # self.stack_tabWidget.setTabText(self.stack_tabWidget.indexOf(self.tab), _translate("MainWindow", "Tab 1"))
        # self.stack_tabWidget.setTabText(self.stack_tabWidget.indexOf(self.tab_2), _translate("MainWindow", "Tab 2"))

        self.menu.setTitle(_translate("MainWindow", "菜单"))
        self.file_menu.setTitle(_translate("MainWindow", "保存"))
        self.save_menu.setTitle(_translate("MainWindow", "状态"))
        self.plot_save_action.setText(_translate("MainWindow", "保存图片"))
        self.save_pushButton.setText(_translate("MainWindow", "点击保存"))

    def draw_all_stack_tab(self):
        # 绘制所有图像
        # 添加到stack_tabWidget上

        # 创建matplot画布
        self.tab1 = PlotCanvas(self, width=9, height=6, dpi=100)
        self.tab2 = PlotCanvas(self, width=9, height=6, dpi=100)
        self.tab3 = PlotCanvas(self, width=9, height=6, dpi=100)
        # mpl.draw_one_line()

        # 加载数据
        # 在不同的画布上画出来
        # 将所有f分页加入到tabWidget上
        lines = load_all_lines()

        self.tab1.draw_one_line(lines[0])
        self.tab2.draw_one_line(lines[1])
        self.tab3.draw_one_line(lines[2])

        # 将所有的tab添加到stack_tabWidget上
        self.stack_tabWidget.addTab(self.tab1, 'td=0.12')
        self.stack_tabWidget.addTab(self.tab2, 'td=0.144')
        self.stack_tabWidget.addTab(self.tab3, 'td=0.176')
        pass

    def set_all_stack_tab_toolbar(self):
        # 添加图像的工具栏 所有的工具栏用容器toolbar_stackedWidget保存
        self.add_stack_toolbar()
        self.tab1_ntb = NavigationToolbar(self.tab1,
                                          self.toolbar_page1)  # 添加完整的 toolbar
        self.tab2_ntb = NavigationToolbar(self.tab2,
                                          self.toolbar_page2)  # 添加完整的 toolbar
        self.tab3_ntb = NavigationToolbar(self.tab3,
                                          self.toolbar_page3)  # 添加完整的 toolbar

        self.tab1.mpl_nav_toolbar = self.tab1_ntb
        self.tab2.mpl_nav_toolbar = self.tab2_ntb
        self.tab3.mpl_nav_toolbar = self.tab3_ntb
        # log('设置了的')
        pass

    def show_status_bar(self):
        # 添加状态栏
        self.status_text = QLabel(" demo 状态栏")
        self.statusbar.addWidget(self.status_text, 1)

    def add_stack_toolbar(self):
        # 添加matplotlib的工具栏
        # toolbar_stackedWidget

        # 创建QStackedWidget容器 将matplotlib所有图像的工具栏叠加放在一起
        # self.toolbar_stackedWidget = QStackedWidget()

        # 创建不同的 QWidget保存单个matplotlib图像的工具栏
        self.toolbar_page1 = QtWidgets.QWidget()
        self.toolbar_page1.setObjectName("toolbar_page1")

        self.toolbar_page2 = QtWidgets.QWidget()
        self.toolbar_page2.setObjectName("toolbar_page2")

        self.toolbar_page3 = QtWidgets.QWidget()
        self.toolbar_page3.setObjectName("toolbar_page3")

        # 初始化空白toolbar区域
        # 添加三个空页
        self.toolbar_stackedWidget.addWidget(self.toolbar_page1)
        self.toolbar_stackedWidget.addWidget(self.toolbar_page2)
        self.toolbar_stackedWidget.addWidget(self.toolbar_page3)

        pass

    def events_all_siganl_connect(self):
        # 连接所有的事件

        # 切换tabWidget图像 显示 当前图像的toolbar
        self.stack_tabWidget.currentChanged.connect(
            self.event_change_toolbar_page)

        # 点击按钮 保存当前图像
        self.save_pushButton.clicked.connect(self.save_plot)

        pass

    def event_change_toolbar_page(self):
        # 切换当前td图像触发
        # 在toolbar_stackedWidget区域显示当前图像的matplotlib工具栏

        # 获取当前的tab
        # log('点击了当前的widget')
        c = self.stack_tabWidget.currentIndex()
        # 设置当前stackWidget的当前
        self.toolbar_stackedWidget.setCurrentIndex(c)
        # log("toolbar_stackedWidget 当前页面是({})".format(c))
        # 设置当前的tool stackWidget的page
        pass

    def get_current_path(self):
        # 获取当前文件目录
        paths = sys.path
        current_file = os.path.basename(__file__)
        for path in paths:
            try:
                if current_file in os.listdir(path):
                    self.current_path = path
                    break
            except (FileExistsError, FileNotFoundError) as e:
                print(e)
Beispiel #19
0
class OknoSwiat(QWidget):
    def __init__(self, swiat):
        super().__init__()
        self.__swiat = swiat
        self.setWindowTitle("Michał Baranowski 165463")
        self.__screen = QDesktopWidget().screenGeometry()
        self.__wys = self.__screen.height()
        self.__szer = self.__screen.width()
        self.setGeometry(0, 0, self.__szer, self.__wys)

        self.__plansza = Plansza(swiat)
        self.__plansza.setGeometry(0, 0, self.__szer, self.__wys / 2)

        self.__buforowane = QStackedWidget()
        self.__buforowane.setGeometry(0, 0, self.__szer, self.__wys / 2)
        self.__buforowane.setMaximumHeight(self.__wys / 2)
        self.__buforowane.addWidget(self.__plansza)

        self.__komunikaty = QLabel()
        self.__komunikaty.setMaximumWidth(self.__szer / 2 - 100)
        self.__komunikaty.setMaximumHeight(self.__wys / 4)
        self.__komunikaty.setAlignment(Qt.AlignTop)
        self.__komunikaty.setText("roboczy tekst")
        self.__komunikaty.setWordWrap(True)

        self.__sterowanie = QLabel()
        self.__sterowanie.setMaximumWidth(self.__szer / 2 - 100)
        self.__sterowanie.setMaximumHeight(self.__wys / 4)
        self.__sterowanie.setAlignment(Qt.AlignTop)
        self.__sterowanie.setText("roboczy 2")
        self.__sterowanie.setWordWrap(True)

        nowa_tura = QPushButton("Nowa Tura", self)
        nowa_tura.setMaximumHeight(self.__wys / 10)
        nowa_tura.setMaximumWidth(self.__szer / 10)
        nowa_tura.clicked.connect(self.on_click_nowa_tura)
        nowa_tura.setFocusPolicy(Qt.NoFocus)

        zapisz_b = QPushButton("Zapisz Stan", self)
        zapisz_b.setMaximumHeight(self.__wys / 10)
        zapisz_b.setMaximumWidth(self.__szer / 10)
        zapisz_b.clicked.connect(self.on_click_zapisz)
        zapisz_b.setFocusPolicy(Qt.NoFocus)

        wczytaj_b = QPushButton("Wczytaj Stan", self)
        wczytaj_b.setMaximumHeight(self.__wys / 10)
        wczytaj_b.setMaximumWidth(self.__szer / 10)
        wczytaj_b.clicked.connect(self.on_click_wczytaj)
        wczytaj_b.setFocusPolicy(Qt.NoFocus)

        panel_komunikacji = QGroupBox()
        info_layout = QHBoxLayout()
        info_layout.addWidget(self.__komunikaty)
        info_layout.addWidget(self.__sterowanie)
        panel_komunikacji.setLayout(info_layout)
        panel_komunikacji.setMaximumHeight(self.__wys / 4)

        panel_przyciskow = QGroupBox()
        button_layout = QHBoxLayout()
        button_layout.addWidget(nowa_tura)
        button_layout.addWidget(zapisz_b)
        button_layout.addWidget(wczytaj_b)
        panel_przyciskow.setLayout(button_layout)
        panel_przyciskow.setMaximumHeight(self.__wys / 4)

        main_layout = QVBoxLayout()
        main_layout.addWidget(self.__buforowane)
        main_layout.addWidget(panel_komunikacji)
        main_layout.addWidget(panel_przyciskow)
        self.setLayout(main_layout)

    def rysuj_organizmy(self):
        self.__plansza.rysuj_organizmy()

    def reset_planszy(self):
        self.__buforowane.removeWidget(self.__plansza)
        self.__plansza = Plansza(self.__swiat)
        self.__buforowane.addWidget(self.__plansza)

    def ustaw_komunikaty(self):
        caly_tekst = ""
        for info in self.__swiat.get_komunikaty():
            caly_tekst += info
            caly_tekst += "\n"
        self.__komunikaty.setText(caly_tekst)

    def ustaw_panel_sterowania(self, opcja=None):
        caly_tekst = ""
        caly_tekst += "Lista dostępnych akcji: \n"
        czlowiek_zyje = False
        licznik = -1
        # sprawdź czy Człowiek żyje i spisz licznik:
        for org in self.__swiat.get_organizmy():
            if isinstance(org, Czlowiek):
                czlowiek_zyje = True
                licznik = org.get_licznik_tarczy()
                break
        if czlowiek_zyje:
            caly_tekst += ">> klawisze strzałek (prawo, lewo, góra, dół) - ruch Człowieka \n"
            if licznik > 5:
                caly_tekst += "TARCZA ALZURA JEST AKTYWNA \n"
            elif licznik > 0:
                caly_tekst += ("Tarcza Alzura będzie aktywna za " +
                               str(licznik))
                if licznik == 5:
                    caly_tekst += " tur \n"
                elif licznik == 1:
                    caly_tekst += " turę \n"
                else:
                    caly_tekst += " tury \n"
            elif licznik == 0:
                caly_tekst += ">> SPACJA - aktywacja Tarczy Alzura \n"
        else:
            caly_tekst += ">> klawisze strzalek /spacja - kolejna tura \n"

        caly_tekst += ">> dedykowane przyciski - kolejna tura, zapis, odczyt i zakończenie \n"
        caly_tekst += ">> kliknięcie myszką w puste pole - dodanie nowego organizmu z listy \n"
        if opcja is not None:
            caly_tekst += opcja
        self.__sterowanie.setText(caly_tekst)

    def on_click_nowa_tura(self):
        self.__swiat.wykonaj_ture()

    def on_click_zapisz(self):
        self.__swiat.zapisz_swiat()
        self.ustaw_panel_sterowania("Stan gry zapisany do pliku. ")

    def on_click_wczytaj(self):
        self.__swiat.wczytaj_swiat()

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Escape:
            self.close()
        elif event.key() == Qt.Key_Up:
            self.__swiat.set_kierunek(Akcje.gora)
            self.__swiat.wykonaj_ture()
        elif event.key() == Qt.Key_Down:
            self.__swiat.set_kierunek(Akcje.dol)
            self.__swiat.wykonaj_ture()
        elif event.key() == Qt.Key_Right:
            self.__swiat.set_kierunek(Akcje.prawo)
            self.__swiat.wykonaj_ture()
        elif event.key() == Qt.Key_Left:
            self.__swiat.set_kierunek(Akcje.lewo)
            self.__swiat.wykonaj_ture()
        elif event.key() == Qt.Key_Space:
            self.__swiat.set_kierunek(Akcje.spacja)
            self.__swiat.wykonaj_ture()
        else:
            pass