class MessageBoxWithList(QMessageBox): def __init__(self, parent = None): super().__init__(parent) self._listWidget = QListWidget(self) self.layout().addWidget(self._listWidget, 3, 1) self._listWidget.hide() def addToList(self, val): self._listWidget.addItem(val) def listCount(self): return self._listWidget.count() def exec(self): if self._listWidget.count() > 0: self._listWidget.show() else: self._listWidget.hide() super().exec()
class MiVentanasegundaria(QWidget): # Creamos una señal para manejar la respuesta del thread threads_response = pyqtSignal(object) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.init_gui() self.thread = None self.texto = Texto() def init_gui(self): # Configuramos los widgets de la interfaz self.resize(1500, 1000) self.label_1 = QLabel( "Bienvenido a Interaula, ingrese nombre de usuario y password", self) self.label_1.setFont(QFont("Sans Serif", 20)) self.label_1.move(350, 100) self.boton = QPushButton("Ingresar", self) self.boton.move(500, 650) self.label2 = QLabel("Usuario", self) self.label3 = QLabel("Password", self) self.label2.move(300, 400) self.label3.move(300, 450) self.user_line = QLineEdit(self) self.pass_line = QLineEdit(self) self.user_line.resize(200, 20) self.pass_line.resize(200, 20) self.user_line.move(400, 400) self.pass_line.move(400, 450) self.pass_line.setEchoMode(QLineEdit.Password) self.user_line.show() self.pass_line.show() self.imagen = QLabel("", self) self.imagen.move(20, 20) pixmap = QPixmap("misc/interaula.png") pixmap = pixmap.scaled(100, 100) self.imagen.setPixmap(pixmap) self.imagen.show() self.setWindowTitle('Interaula - Profesor') self.show() self.boton.clicked.connect(self.menu) def menu(self): self.usuario = Profesor(self.user_line.text(), self.pass_line.text()) QTest.qWait(500) if self.usuario.connected: self.label_1.setText("Bienvenido " + self.usuario.name) self.label2.hide() self.label3.hide() self.user_line.hide() self.pass_line.hide() self.boton.hide() ##### self.label2.setText("Ingrese a un curso o cree uno nuevo") self.label2.move(100, 200) ### Creamos tabla con los cursos disponibles self.tabla = QListWidget(self) self.tabla.addItem( "Sigla Nombre Curso Profesor " ) self.tabla.resize(700, 400) self.tabla.move(200, 200) i = 0 for item in self.usuario.clases: self.tabla.addItem( str(item[0]) + " " + str(item[1] + " " + str(self.usuario.name))) self.tabla.itemClicked.connect(self.connect_curso) self.tabla.show() ### self.boton_crear = QPushButton("Crear Curso", self) self.boton_crear.move(500, 600) self.boton_crear.show() self.boton_crear.clicked.connect(self.crear_curso) else: self.label4 = QLabel( "Usuario o password incorrectos, intente nuevamente", self) self.label4.move(400, 730) self.label4.show() def connect_curso(self, item): items = item.text().split( " ") self.label_1.setText("{}".format(items[1]).capitalize()) self.usuario.get_clases(items[0]) self.curso_actual = items[0] QTest.qWait(200) self.label2.setText("Elija una clase o cree una nueva") self.label2.show() self.combo_box = QComboBox(self) for elemento in self.usuario.clases_actuales: self.combo_box.addItem(str(elemento[2])) self.combo_box.move(300, 300) self.combo_box.show() self.boton_cargar = QPushButton("Cargar Clase", self) self.boton_cargar.move(300, 500) self.boton_cargar.show() self.boton_crear2 = QPushButton("Crear Clase", self) self.boton_crear2.move(500, 500) self.boton_crear2.show() self.boton_crear2.clicked.connect(self.crear_clase) self.boton_crear.hide() self.tabla.hide() def crear_curso(self): self.dialog = QDialog() self.dialog.resize(500, 500) label1 = QLabel("Ingrese Sigla: ", self.dialog) label2 = QLabel("Ingrese nombre Curso :", self.dialog) label1.move(60, 100) label2.move(60, 200) self.line_edit1 = QLineEdit(self.dialog) self.line_edit2 = QLineEdit(self.dialog) self.line_edit1.move(230, 100) self.line_edit2.move(230, 200) b1 = QPushButton("Crear", self.dialog) b1.move(300, 400) self.dialog.show() b1.clicked.connect(self.crear) def crear(self): self.usuario.crear_curso(self.line_edit1.text(), self.line_edit2.text()) QTest.qWait(300) self.dialog.hide() self.menu() def crear_clase(self): self.combo_box.hide() self.boton_crear2.hide() self.boton_cargar.hide() self.label2.setText( "Ingese numero de clase. Asegurate que el pdf esté en la misma carpeta con el mismo nombre" ) self.label2.resize(800, 20) self.line_edit3 = QLineEdit(self) self.line_edit3.move(400, 500) self.boton_iniciar = QPushButton("Crear", self) self.boton_iniciar.move(500, 600) self.line_edit3.show() self.boton_iniciar.show() self.boton_iniciar.clicked.connect(self.empezar_clase) def empezar_clase(self): self.usuario.clase_en_vivo(self.line_edit3.text(), self.curso_actual) self.imagen.hide() self.label_1.hide() self.clase_actual = self.line_edit3.text() self.numero = str(self.line_edit3.text()) self.diapos_totales = len([ f for f in listdir(self.numero + "/") if isfile(join(self.numero + "/", f)) and ".jpg" in f ]) self.registro = [["Diapositiva {}".format(i)] for i in range(1, self.diapos_totales + 1)] self.line_edit3.hide() self.boton_iniciar.hide() # Configuramos los widgets de la interfaz self.diapositivas = QLabel("", self) # self.diapositivas.move() pixmap = QPixmap("1/1.jpg") pixmap = pixmap.scaled(650, 450) self.diapositivas.setPixmap(pixmap) self.diapositivas.show() self.diapositivas.move(100, 120) self.label = QLabel('Esperando inicio', self) self.label.setFont(QFont("Sans Serif", 25)) self.boton = QPushButton('Iniciar escucha', self) self.boton.clicked.connect(self.start_threads) self.tabla = QListWidget(self) self.tabla.addItem("Diapositiva 1") self.boton_2 = QPushButton("Guardar", self) self.boton_2.move(200, 700) self.boton_2.clicked.connect(self.guardar_archivo) self.boton_3 = QPushButton("Siguiente", self) self.boton_3.move(400, 600) self.boton_4 = QPushButton("Anterior", self) self.boton_4.move(200, 600) self.label.show() self.boton.show() self.tabla.show() self.boton_2.show() self.boton_3.show() self.boton_4.show() self.boton_3.clicked.connect(self.siguiente) self.boton_4.clicked.connect(self.anterior) self.tabla.resize(400, 600) self.tabla.move(800, 100) self.label.resize(1000, 30) self.label.move(100, 50) self.boton.move(50, 700) self.resize(1500, 1000) self.diapo = 1 # Conectamos la señal del thread al método que maneja self.threads_response.connect(self.update_labels) def start_threads(self): self.boton.setText("Detener Escucha") self.boton.clicked.connect(self.detener) if self.thread is None or not self.thread.is_alive(): self.thread = MiThread(self.threads_response, daemon=True) self.thread.start() def detener(self): self.thread.stop_thread() self.usuario.terminar_clase(self.numero, self.curso_actual) def update_labels(self, evento): self.label.setText("[PROFESOR] " + evento.msg) self.usuario.send_translate("[PROFESOR] " + evento.msg, self.curso_actual) self.registro[self.diapo - 1].append("[PROFESOR] " + evento.msg) self.tabla.addItem("[PROFESOR] " + evento.msg) def guardar_archivo(self): text = QLabel("Clase Creada Con Exito!") self.thread.stop_thread() print(self.registro) print(self.curso_actual) print(self.clase_actual) self.usuario.crear_clase(self.registro, self.curso_actual, self.clase_actual) def anterior(self): self.usuario.anterior(self.curso_actual) self.diapo -= 1 if self.diapo >= 1: self.tabla.clear() self.texto.back_diap() pixmap = QPixmap("1/{}.jpg".format(self.diapo)) pixmap = pixmap.scaled(650, 450) self.diapositivas.setPixmap(pixmap) for i in self.registro[int(self.diapo - 1)]: self.tabla.addItem(i) else: self.diapo += 1 def siguiente(self): self.usuario.siguiente(self.curso_actual) self.diapo += 1 if self.diapo <= self.diapos_totales: self.tabla.clear() self.texto.back_diap() pixmap = QPixmap("1/{}.jpg".format(self.diapo)) pixmap = pixmap.scaled(650, 450) self.diapositivas.setPixmap(pixmap) for i in self.registro[int(self.diapo - 1)]: self.tabla.addItem(i) else: self.diapo -= 1
class MainWindow(DATA[0], DATA[1]): def __init__(self): super().__init__() self.setupUi(self) self.scrollArea.hide() self.label_6.hide() self.pushButton.clicked.connect(self.iniciar_sesion) self.setWindowTitle("PrograPop") self.scrollArea_2.hide() self.label_tiempo = QLabel("20", self) self.label_tiempo.move(500, 300) self.label_tiempo.resize(100,100) self.label_tiempo.setFont(QFont("SansSerif", 20)) self.label_tiempo.hide() self.song_name = None self.song = None self.salas = [{"name": "Recibiendo Canciones, pulsa actualizar!", "usuarios":[], "artistas": "None", "tiempo_restante": 0}] self.a = 0 self.chat = QListWidget(self) self.chat.resize(1000, 300) self.chat.move(30,370) self.chat.hide() self.puntajes = None self.login = False def iniciar_sesion(self): self.name = self.lineEdit.text() self.setWindowTitle("PrograPop ({})".format(self.name)) self.usuario_back = BE_Client.Client_Back(self) while not self.login: pass time.sleep(2) self.usuario_back.get_salas() time.sleep(2) self.usuario_back.get_info() time.sleep(0.2) self.label_6.setText("Bienvenido {}\nTienes {} puntos".format(self.name, self.usuario_back.puntos)) self.label_6.show() self.lineEdit.hide() self.label_2.hide() self.pushButton.hide() self.titulo.setText("Elige una Sala") self.label_inferior = QLabel("Haz click sobre una sala para ingresar", self) self.label_inferior.move(500,200) self.label_inferior.show() self.lista_items = QListWidget(self) for item in self.salas: self.lista_items.addItem("Sala : {}, Usuarios: {}, artistas: {}, tº restante: {}".format(item["name"], len(item["usuarios"]), item["artistas"], item["tiempo_restante"])) self.lista_items.show() self.lista_items.resize(600,200) self.lista_items.move(300,200) self.lista_items.itemClicked.connect(self.conectarse_sala) self.actualizar = QPushButton("Actualizar", self) self.actualizar.move(1000, 100) self.actualizar.show() self.actualizar.clicked.connect(self.actualizar_salas) self.tabla_de_puntos = QPushButton("Tabla de puntajes", self) self.tabla_de_puntos.move(40, 600) self.tabla_de_puntos.resize(200,20) self.tabla_de_puntos.show() self.tabla_de_puntos.clicked.connect(self.puntos_dialog) def conectarse_sala(self, item): self.label_inferior.hide() self.tabla_de_puntos.hide() self.lista_items.hide() name = item.text().split(",")[0].split(":")[1].replace(" ", "") self.sala_actual = name self.usuario_back.connect_sala(name) self.usuario_back.get_info() self.scrollArea.hide() self.titulo.setText(name) self.label_6.hide() self.actualizar.hide() self.volver = QPushButton("Salir", self) self.volver.move(30, 30) self.volver.clicked.connect(self.volver_menu) self.volver.show() # Tabla de puntajes self.tabla_puntajes_sala = QListWidget(self) self.tabla_puntajes_sala.resize(200, 100) self.tabla_puntajes_sala.move(930, 200) self.tabla_puntajes_sala.addItem("Puntajes") self.tabla_puntajes_sala.show() # CHAT self.chat.show() self.chat.addItem("Chat") self.line_chat = QLineEdit(self) self.line_chat.move(40, 690) self.line_chat.resize(1000, 30) self.chatButton = QPushButton("Enviar", self) self.chatButton.move(1050, 690) self.chatButton.show() self.line_chat.show() self.chatButton.clicked.connect(self.enviar_mensaje) # Tabla de tiempos self.sala_tabla = QListWidget(self) self.sala_tabla.resize(200,100) self.sala_tabla.move(930,30) self.sala_tabla.addItem("Tiempos") self.sala_tabla.show() # Juego self.opcion1 = QPushButton("opcion1", self) self.opcion2 = QPushButton("opcion2", self) self.opcion3 = QPushButton("opcion3 ", self) self.opcion1.move(30, 200) self.opcion2.move(400, 200) self.opcion3.move(700, 200) self.opcion1.resize(200,30) self.opcion2.resize(200, 30) self.opcion3.resize(200, 30) self.opcion1.clicked.connect(self.opcion_selecta) self.opcion2.clicked.connect(self.opcion_selecta) self.opcion3.clicked.connect(self.opcion_selecta) while self.sala_actual != None: while not self.song_name: pass self.song = QSound(self.song_name) self.song_name = None self.song.play() self.label_tiempo.show() self.opcion1.show() self.opcion2.show() self.opcion3.show() QTest.qWait(1000) QTest.qWait(1000) self.label_tiempo.setText("19") QTest.qWait(1000) self.label_tiempo.setText("19") QTest.qWait(1000) self.label_tiempo.setText("17") QTest.qWait(1000) self.label_tiempo.setText("16") QTest.qWait(1000) self.label_tiempo.setText("15") QTest.qWait(1000) self.label_tiempo.setText("14") QTest.qWait(1000) self.label_tiempo.setText("13") QTest.qWait(1000) self.label_tiempo.setText("12") QTest.qWait(1000) self.label_tiempo.setText("11") QTest.qWait(1000) self.label_tiempo.setText("10") QTest.qWait(1000) self.label_tiempo.setText("9") QTest.qWait(1000) self.label_tiempo.setText("8") QTest.qWait(1000) self.label_tiempo.setText("7") QTest.qWait(1000) self.label_tiempo.setText("6") QTest.qWait(1000) self.label_tiempo.setText("5") QTest.qWait(1000) self.label_tiempo.setText("4") QTest.qWait(1000) self.label_tiempo.setText("3") QTest.qWait(1000) self.label_tiempo.setText("2") QTest.qWait(1000) self.label_tiempo.setText("1") QTest.qWait(1000) self.opcion1.hide() self.opcion2.hide() self.opcion3.hide() self.sala_tabla.clear() self.sala_tabla.addItem("Tiempos") self.label_tiempo.hide() self.label_tiempo.setText("20") self.chat.addItem("Server: Preparate para la siguiente ronda") self.song.stop() QTest.qWait(1000) def actualizar_salas(self): self.lista_items.clear() self.usuario_back.get_salas() time.sleep(0.2) for item in self.salas: self.lista_items.addItem("Sala : {}, Usuarios: {}, artistas: {}, tº restante : {}".format(item["name"], len(item["usuarios"]), item["artistas"], item["tiempo_restante"])) def volver_menu(self): self.tabla_puntajes_sala.clear() self.tabla_puntajes_sala.addItem("Puntajes") self.tabla_puntajes_sala.hide() self.sala_tabla.clear() self.sala_tabla.hide() self.tabla_de_puntos.show() self.chat.clear() self.chat.hide() self.usuario_back.get_salas() time.sleep(0.2) self.usuario_back.disconnect_sala(self.sala_actual) time.sleep(0.2) self.usuario_back.get_info() time.sleep(0.2) self.sala_actual = None self.song.stop() self.titulo.setText("Elige una Sala") self.label_6.setText("Bienvenido {}\nTienes {} puntos".format(self.name, self.usuario_back.puntos)) self.label_6.show() self.label.setText("Nombre: {} - Usuarios : {} - Artistas : {}" .format(self.salas[0]["name"], len(self.salas[0]["usuarios"]), self.salas[0]["artistas"])) self.lista_items.show() self.actualizar.show() self.volver.hide() self.line_chat.hide() self.chatButton.hide() self.scrollArea_2.hide() self.opcion1.hide() self.opcion2.hide() self.opcion3.hide() def enviar_mensaje(self): mensaje = self.line_chat.text() self.line_chat.setText("") self.usuario_back.chat(mensaje, self.sala_actual) def opcion_selecta(self): boton = self.sender() self.opcion1.hide() self.opcion2.hide() self.opcion3.hide() self.usuario_back.desicion(boton.text()) def puntos_dialog(self): dialog = QDialog(self) dialog.resize(500,500) tabla1 = QListWidget(dialog) tabla1.resize(150,400) tabla1.move(20,20) tabla1.addItem("Tabla de Puntajes") dialog.setWindowTitle("Puntajes - Presiona Esc para salir") self.usuario_back.get_puntajes() while not self.puntajes: pass for item in self.puntajes: tabla1.addItem("{} : {} puntos".format(item[0], item[1])) tabla1.show() label_facil = QLabel("Sala mas facil : {}".format(self.sala_facil), dialog) label_dificil = QLabel("Sala mas dificl: {}".format(self.sala_dificl), dialog) label_dificil.move(300,50) label_facil.move(300, 250) label_dificil.show() label_facil.show() dialog.show()
class MainWindow(CenterWindow): """ Displays list with tasks assigned to current user in JIRA """ def __init__(self, controller): super().__init__() self.setStyleSheet(QSS) self.controller = controller self.resize(1000, 600) self.setWindowTitle('JIRA Quick Reporter') self.setWindowIcon(QIcon(LOGO_PATH)) self.center() self.current_item = None self.vbox = QVBoxLayout() self.save_btn_box = QHBoxLayout() self.filter_name_label = QLabel() self.filter_name_label.setObjectName('filter_name_label') self.filter_name_label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.filter_name_label.setAlignment(Qt.AlignLeft) self.filter_edited_label = QLabel('-> edited') self.filter_edited_label.setObjectName('filter_edited_label') self.filter_edited_label.hide() self.filter_edited_label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.save_filter_btn = QPushButton('Save as') self.save_filter_btn.setObjectName('save_filter_btn') self.save_filter_btn.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.save_filter_btn.clicked.connect(self.controller.save_filter) self.overwrite_filter_button = QPushButton('Save') self.overwrite_filter_button.setToolTip('You need to edit filter query first') self.overwrite_filter_button.setObjectName('save_filter_btn') self.overwrite_filter_button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.overwrite_filter_button.clicked.connect(lambda: self.controller.save_filter(True)) self.delete_filter_btn = QPushButton() self.delete_filter_btn.setObjectName('delete_filter_btn') self.delete_filter_btn.clicked.connect(self.delete_filter) self.delete_filter_btn.setIcon(QIcon(DELETE_FILTER_ICON)) self.delete_filter_btn.setIconSize( QSize( self.delete_filter_btn.sizeHint().height(), self.delete_filter_btn.sizeHint().height() ) ) self.delete_filter_btn.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.delete_filter_btn.setToolTip('Delete filter') self.save_btn_box.addWidget(self.filter_name_label, Qt.AlignLeft) self.save_btn_box.addWidget(self.filter_edited_label, Qt.AlignLeft) self.save_btn_box.addWidget(self.save_filter_btn, Qt.AlignLeft) self.save_btn_box.addWidget(self.overwrite_filter_button, Qt.AlignLeft) self.save_btn_box.addStretch() self.save_btn_box.addWidget(self.delete_filter_btn, Qt.AlignRight) self.create_filter_box = QHBoxLayout() self.query_field = QLineEdit() self.query_field.setObjectName('query_field') self.query_field.setPlaceholderText('You need to write a query here') self.action_help = QAction() self.action_help.setIcon(self.style().standardIcon(QStyle.SP_MessageBoxQuestion)) self.help_filter_url = QUrl(FILTER_FIELD_HELP_URL) self.action_help.triggered.connect(self.filter_field_help) self.query_field.addAction(self.action_help, QLineEdit.TrailingPosition) self.query_field.installEventFilter(self) self.search_issues_button = QPushButton('Search') self.search_issues_button.setObjectName('search_issues_button') self.search_issues_button.clicked.connect(self.controller.search_issues_by_query) self.create_filter_box.addWidget(self.query_field) self.create_filter_box.addWidget(self.search_issues_button) self.list_box = QVBoxLayout() self.issue_list_widget = QListWidget() self.issue_list_widget.setObjectName('issue_list') self.label_info = QLabel('You have no issues.') self.label_info.setAlignment(Qt.AlignCenter) self.list_box.addWidget(self.issue_list_widget) self.list_box.addWidget(self.label_info) self.label_info.hide() self.vbox.addLayout(self.save_btn_box) self.vbox.addLayout(self.create_filter_box) self.vbox.addLayout(self.list_box) self.filters_frame = QFrame() self.filters_frame.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding) self.filters_frame.setFrameShape(QFrame.StyledPanel) self.filters_frame.setObjectName('filters_frame') self.filters_box = QVBoxLayout(self.filters_frame) self.filters_box_label = QLabel('Issues and filters') self.filters_box_label.setObjectName('filters_box_label') self.filters_box.addWidget(self.filters_box_label) self.filters_list = QListWidget() self.filters_list.installEventFilter(self) self.filters_list.itemClicked.connect(self.on_filter_selected) self.filters_list.setObjectName('filters_list') self.filters_list.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.filters_box.addWidget(self.filters_list) self.add_filter_button = QPushButton('+') self.add_filter_button.clicked.connect(self.add_filter_btn_click) self.add_filter_button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.filters_box.addWidget(self.add_filter_button, alignment=Qt.AlignRight) self.btn_box = QHBoxLayout() self.refresh_btn = QPushButton('Refresh') self.refresh_btn.clicked.connect(self.controller.refresh_issue_list) self.btn_box.addWidget(self.refresh_btn, alignment=Qt.AlignRight) self.vbox.addLayout(self.btn_box) self.toggle_frame_filters_btn = QPushButton('<') self.toggle_frame_filters_btn.clicked.connect(self.toggle_frame_filters) self.toggle_frame_filters_btn.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.toggle_frame_filters_btn.setObjectName('toggle_filters_btn') self.main_box = QHBoxLayout() self.main_box.addWidget(self.filters_frame) self.main_box.addWidget(self.toggle_frame_filters_btn, alignment=Qt.AlignTop) self.main_box.addLayout(self.vbox) self.setLayout(self.main_box) self.tray_icon = QSystemTrayIcon(self) self.tray_icon.setIcon(QIcon(LOGO_PATH)) self.tray_menu = QMenu() self.action_open = QAction('Open JQR', self) self.action_quit = QAction('Quit JQR', self) self.tray_menu.addAction(self.action_open) self.action_open.triggered.connect(self.show_jqr_from_tray) self.tray_menu.addAction(self.action_quit) self.action_quit.triggered.connect(self.controller.quit_app) self.tray_icon.setContextMenu(self.tray_menu) self.tray_icon.show() self.timer_log_work = QTimer() self.timer_log_work.timeout.connect(self.notification_to_log_work) self.timer_log_work.start(LOG_TIME) self.timer_refresh = QTimer() self.timer_refresh.timeout.connect(self.controller.auto_refresh_issue_list) def show_jqr_from_tray(self): self.hide() self.setWindowFlags(self.windowFlags() & ~Qt.WindowStaysOnTopHint) self.activateWindow() self.show() def keyPressEvent(self, event): if event.key() == Qt.Key_Return: self.controller.search_issues_by_query() def notification_to_log_work(self): QSound.play(RING_SOUND_PATH) self.tray_icon.showMessage( '1 hour had passed', 'Don\'t forget to log your work!', msecs=2000 ) self.timer_log_work.start(LOG_TIME) def update_issues(self, update_list): for issue in update_list: item = self.issue_list_widget.findItems( issue['key'], Qt.MatchExactly )[0] item.setText(issue['key']) issue_widget = self.issue_list_widget.itemWidget(item) issue_widget.set_issue_key(issue['key'], issue['link']) issue_widget.set_issue_title(issue['title']) issue_widget.set_time( issue['estimated'], issue['logged'], issue['remaining'] ) issue_widget.set_workflow.clear() issue_widget.set_workflow.addItems(self.controller.get_possible_workflows(issue)) issue_widget.set_workflow.setCurrentIndex(0) issue_widget.set_workflow.activated[str].disconnect() issue_widget.set_workflow.activated[str].connect( partial( self.controller.change_workflow, issue['workflow'], issue['issue_obj'], ) ) def delete_issues(self, delete_list): for issue in delete_list: item = self.issue_list_widget.findItems( issue['key'], Qt.MatchExactly )[0] self.issue_list_widget.takeItem( self.issue_list_widget.row(item) ) def insert_issues(self, new_issues_list): for issue in new_issues_list: issue_widget = QCustomWidget() issue_widget.set_issue_key(issue['key'], issue['link']) issue_widget.set_issue_title(issue['title']) issue_widget.set_time( issue['estimated'], issue['logged'], issue['remaining'] ) issue_widget.quick_log_btn.clicked.connect( partial( self.controller.log_work_from_list, issue['key'] ) ) issue_widget.log_work_btn.clicked.connect( partial( self.controller.open_time_log, issue['key'] ) ) issue_widget.open_pomodoro_btn.clicked.connect( partial( self.controller.open_pomodoro_window, issue['key'], issue['title'] ) ) # add workflow statuses to dropdown possible_workflows = self.controller.get_possible_workflows(issue) issue_widget.set_workflow.addItems(possible_workflows) issue_widget.set_workflow.setCurrentIndex(0) issue_widget.set_workflow.activated[str].connect( partial( self.controller.change_workflow, issue['workflow'], issue['issue_obj'], ) ) # add issue item to list issue_list_widget_item = QListWidgetItem() issue_list_widget_item.setText(issue['key']) issue_list_widget_item.setSizeHint(issue_widget.sizeHint()) self.issue_list_widget.insertItem(issue['index'], issue_list_widget_item) self.issue_list_widget.setItemWidget( issue_list_widget_item, issue_widget ) self.set_size_hint() def set_size_hint(self): self.issue_list_widget.setMinimumWidth( self.issue_list_widget.sizeHintForColumn(0) + 50 ) self.issue_list_widget.setMinimumHeight( self.issue_list_widget.sizeHintForRow(0) * 2 ) def show_filters(self, filters_dict): for index, key in enumerate(filters_dict): if key == SEARCH_ITEM_NAME: self.filters_list.insertItem(0, key) else: self.filters_list.addItem(key) self.filters_list.item(index).setToolTip(key) self.filters_list.item(0).setText(self.filters_list.item(0).text().capitalize()) # add separator after first item separator = QFrame() separator.setFrameShape(QFrame.HLine) separator.setObjectName('separator') item_separator = QListWidgetItem() item_separator.setFlags(Qt.NoItemFlags) self.filters_list.insertItem(1, item_separator) self.filters_list.setItemWidget(item_separator, separator) self.filters_list.setCurrentItem( self.filters_list.findItems( MY_ISSUES_ITEM_NAME, Qt.MatchExactly )[0]) self.filters_list.setSizeAdjustPolicy(QAbstractScrollArea.AdjustToContents) self.on_filter_selected(self.filters_list.currentItem()) def filter_field_help(self): QDesktopServices.openUrl(self.help_filter_url) def on_filter_selected(self, item): if not item.text(): return self.current_item = item if len(self.current_item.text()) > 50: set_text = '{}...'.format(self.current_item.text()[:50]) else: set_text = self.current_item.text() self.issue_list_widget.scrollToTop() self.controller.search_issues_by_filter_name(item.text()) self.filter_name_label.setText(set_text) self.filter_edited_label.hide() if self.filters_list.currentItem().text() == MY_ISSUES_ITEM_NAME: self.save_filter_btn.hide() self.overwrite_filter_button.hide() self.filter_edited_label.hide() self.delete_filter_btn.hide() elif self.filters_list.currentItem().text() == SEARCH_ITEM_NAME.capitalize(): # activate save button self.overwrite_filter_button.hide() self.save_filter_btn.show() self.delete_filter_btn.hide() else: # activate overwrite button self.overwrite_filter_button.show() self.overwrite_filter_button.setEnabled(False) self.save_filter_btn.hide() self.delete_filter_btn.show() def toggle_frame_filters(self): if self.toggle_frame_filters_btn.text() == '<': self.toggle_frame_filters_btn.setText('>') self.filters_frame.hide() else: self.toggle_frame_filters_btn.setText('<') self.filters_frame.show() def add_filter_btn_click(self): self.overwrite_filter_button.hide() self.save_filter_btn.show() self.delete_filter_btn.hide() self.filter_edited_label.hide() self.filters_list.setCurrentItem(None) self.query_field.setText('') self.filter_name_label.setText('Add new filter') self.controller.current_issues.clear() self.show_no_issues() def eventFilter(self, obj, event): # if user started typing in filter field if obj is self.query_field and event.type() == QEvent.KeyRelease: if not self.filters_list.currentItem(): return super().eventFilter(obj, event) current_filter_name = self.filters_list.currentItem().text().lower() # if current filter is not 'Search issues' or 'my open issues' if current_filter_name not in (SEARCH_ITEM_NAME, MY_ISSUES_ITEM_NAME): # if query of current filter has not changed if self.controller.filters_handler.get_filter_by_name( current_filter_name ) != self.query_field.text(): # show that filter has been edited self.filter_edited_label.show() self.overwrite_filter_button.setEnabled(True) else: self.filter_edited_label.hide() self.overwrite_filter_button.setEnabled(False) return super().eventFilter(obj, event) def set_current_filter(self, filter_name): items = self.filters_list.findItems( filter_name, Qt.MatchExactly ) self.filters_list.setCurrentItem(items[0]) self.on_filter_selected(items[0]) def add_filter(self, filter_name): self.filters_list.addItem(filter_name) self.set_current_filter(filter_name) def delete_filter(self): filter_name = self.filters_list.currentItem().text() reply = QMessageBox.question( self, 'Delete filter', "Are you sure you want to delete " "'{}' filter?".format(filter_name), QMessageBox.Yes | QMessageBox.Cancel ) if reply == QMessageBox.Yes: self.controller.filters_handler.delete_filter(filter_name) self.filters_list.takeItem( self.filters_list.currentRow() ) self.filters_list.setCurrentItem( self.filters_list.findItems( MY_ISSUES_ITEM_NAME, Qt.MatchExactly )[0]) self.on_filter_selected(self.filters_list.currentItem()) def show_no_issues(self, error_text=None): self.issue_list_widget.clear() self.issue_list_widget.hide() if error_text: self.label_info.setText(error_text) self.label_info.show() def set_workflow_current_state(self, issue_key): item = self.issue_list_widget.findItems( issue_key, Qt.MatchExactly )[0] custom_item = self.issue_list_widget.itemWidget(item) custom_item.set_workflow.setCurrentIndex(0) def wheelEvent(self, event): # top left corner coordinates of the issue list list_pos = self.issue_list_widget.pos() # check if cursor position is on the issue list if event.pos().x() >= list_pos.x() and event.pos().y() >= list_pos.y(): if event.angleDelta().y() < 0: self.controller.refresh_issue_list(True) event.accept() def closeEvent(self, event): event.ignore() self.hide()
class AdminWindow(QWidget): def __init__(self, db_connection): super().__init__() self.db_connection = db_connection self.create_window() def create_window(self): self.setGeometry(300, 300, 900, 450) #x, y, w, h self.setWindowTitle('3D Printers DB - Administrator ') self.main_layout = QHBoxLayout(self) self.create_menu() self.menu_spacer = QSpacerItem(40, 10) self.main_layout.addItem(self.menu_spacer) self.create_welcome_message_layout() self.create_assign_print_layout() self.create_what_is_printed_layout() self.create_finish_print_layout() self.create_customer_leaderboards_layout() self.create_earnings_statistics_layout() def create_menu(self): self.menu = QVBoxLayout(self) self.menu_description = QLabel('Administrator Window', self) font = QFont() font.setPixelSize(20) font.setBold(True) self.menu_description.setFont(font) self.finish_print_btn = QPushButton('Finish print', self) self.customer_leaderboards_btn = QPushButton('Customer leaderboards', self) self.assign_print_btn = QPushButton('Assign print', self) self.what_is_printed_btn = QPushButton('What is printed?', self) self.earnings_statisctics_btn = QPushButton('Earnings Statisctics', self) self.logout_btn = QPushButton('Logout and exit', self) #self.make_order_btn.clicked.connect(self.make_oder_button_trigger) #self.order_history_btn.clicked.connect(self.order_history_button_trigger) #self.profile_btn.clicked.connect(self.profile_button_trigger) self.logout_btn.clicked.connect(self.logout_button_trigger) self.assign_print_btn.clicked.connect(self.assign_print_button_trigger) self.what_is_printed_btn.clicked.connect(self.what_is_printed_button_trigger) self.finish_print_btn.clicked.connect(self.finish_print_button_trigger) self.customer_leaderboards_btn.clicked.connect(self.customer_leaderboards_button_trigger) self.earnings_statisctics_btn.clicked.connect(self.earnings_statistics_button_trigger) self.menu.addWidget(self.menu_description) self.menu.addWidget(self.what_is_printed_btn) self.menu.addWidget(self.assign_print_btn) self.menu.addWidget(self.finish_print_btn) self.menu.addWidget(self.customer_leaderboards_btn) self.menu.addWidget(self.earnings_statisctics_btn) self.menu.addWidget(self.logout_btn) self.menu.addStretch() self.main_layout.addLayout(self.menu) def create_welcome_message_layout(self): self.welcome_message_layout = QVBoxLayout(self) self.welcome_message_font = QFont() self.welcome_message_font.setPixelSize(12) self.welcome_message_text = 'Welcome in Printer DB application in admin mode.\nUse menu ' \ 'located on the left site of window for navigation.' self.welcome_message = QLabel(self.welcome_message_text) self.welcome_message.setFont(self.welcome_message_font) self.welcome_message_layout.addWidget(self.welcome_message) self.welcome_message_layout.addStretch() self.main_layout.addLayout(self.welcome_message_layout) def hide_welcome_message_layout(self): self.welcome_message.hide() def show_welcome_message_layout(self): self.welcome_message.show() def fill_print(self): self.print_field.clear() SQL_command = "SELECT id, stl_filename, due_date, filament_type, filament_color, \ estimated_printing_time FROM print_3d \ WHERE completion_date IS NULL \ AND printer_id IS NULL \ ORDER BY due_date;" cursor = self.db_connection.cursor() cursor.execute(SQL_command) self.prints_to_do = [] res = cursor.fetchone() while res is not None: self.prints_to_do.append(res) self.print_field.addItem(str(res.id) + ', ' + res.stl_filename + ', ' + str(res.due_date)[0:9] +', ' + res.filament_type+', ' + res.filament_color) res = cursor.fetchone() def fill_printers(self): self.printer_field.clear() SQL_command = "SELECT printer_3d.id, manufacturer, model \ FROM printer_3d \ JOIN print_3d on printer_3d.id = print_3d.printer_id \ WHERE completion_date IS NULL" cursor = self.db_connection.cursor() cursor.execute(SQL_command) res = cursor.fetchone() self.busy_printers = [] while res is not None: self.busy_printers.append(res) res = cursor.fetchone() SQL_command = "SELECT printer_3d.id, manufacturer, model \ FROM printer_3d" cursor = self.db_connection.cursor() cursor.execute(SQL_command) res = cursor.fetchone() self.all_printers = [] while res is not None: self.all_printers.append(res) res = cursor.fetchone() free_printers = [] for i in self.all_printers: if i not in self.busy_printers: free_printers.append(i) self.printer_field.addItem(str(i.id) + ', ' + i.manufacturer + ' ' + i.model) def create_assign_print_layout(self): self.assign_print_layout = QVBoxLayout(self) self.assign_print_grid = QGridLayout() self.assign_print_info = QLabel('Assign print: ', self) self.assign_print_info_font = QFont() self.assign_print_info_font.setPixelSize(16) self.assign_print_info_font.setBold(True) self.assign_print_info.setFont(self.assign_print_info_font) self.assign_print_layout.addWidget(self.assign_print_info) self.printer_label = QLabel('Printer:', self) self.printer_field = QListWidget(self) self.print_label = QLabel('Print: ', self) self.print_field = QListWidget(self) self.assign_print_apply_button = QPushButton('Assign', self) self.assign_print_apply_button.clicked.connect(self.print_apply_button_trigger) self.assign_print_grid.addWidget(self.printer_label, 0, 0) self.assign_print_grid.addWidget(self.printer_field, 0, 1) self.assign_print_grid.addWidget(self.print_label, 1, 0) self.assign_print_grid.addWidget(self.print_field, 1, 1) self.assign_print_grid.addWidget(self.assign_print_apply_button, 2, 1) self.assign_print_layout.addLayout(self.assign_print_grid) self.assign_print_layout.addStretch() self.main_layout.addLayout(self.assign_print_layout) self.hide_assign_print_layout() def hide_assign_print_layout(self): self.assign_print_info.hide() self.printer_label.hide() self.printer_field.hide() self.print_label.hide() self.print_field.hide() self.assign_print_apply_button.hide() def show_assign_print_layout(self): self.fill_printers() self.fill_print() self.assign_print_info.show() self.printer_label.show() self.printer_field.show() self.print_label.show() self.print_field.show() self.assign_print_apply_button.show() def create_what_is_printed_layout(self): self.what_is_printed_layout = QVBoxLayout(self) self.what_is_printed_info = QLabel('What is currently printed: ', self) self.what_is_printed_info_font = QFont() self.what_is_printed_info_font.setPixelSize(16) self.what_is_printed_info_font.setBold(True) self.what_is_printed_info.setFont(self.what_is_printed_info_font) self.what_is_printed_layout.addWidget(self.what_is_printed_info) self.what_is_printed_table = QTableWidget(self) self.what_is_printed_layout.addWidget(self.what_is_printed_table) self.main_layout.addLayout(self.what_is_printed_layout) self.what_is_printed_table.setColumnCount(3) self.what_is_printed_table.setHorizontalHeaderLabels(['Printer', 'Filename', 'Customer name']) self.what_is_printed_layout.addWidget(self.what_is_printed_table) self.hide_what_is_printed_layout() def update_what_is_printed_layout(self): SQL_command = "SELECT printer_3d.id, manufacturer, model, stl_filename, customer_username \ FROM printer_3d \ JOIN print_3d on printer_3d.id = print_3d.printer_id \ WHERE completion_date IS NULL" cursor = self.db_connection.cursor() cursor.execute(SQL_command) res = cursor.fetchone() self.busy_printers = [] while res is not None: self.busy_printers.append(res) res = cursor.fetchone() self.what_is_printed_table.setRowCount(len(self.busy_printers)) for i in range(0, len(self.busy_printers)): self.what_is_printed_table.setItem(i, 0, QTableWidgetItem(str(self.busy_printers[i].id) + ' ' +\ self.busy_printers[i].manufacturer + ' ' + \ self.busy_printers[i].model)) self.what_is_printed_table.setItem(i, 1, QTableWidgetItem(self.busy_printers[i].stl_filename)) self.what_is_printed_table.setItem(i, 2, QTableWidgetItem(self.busy_printers[i].customer_username)) def show_what_is_printed_layout(self): self.update_what_is_printed_layout() self.what_is_printed_info.show() self.what_is_printed_table.show() def hide_what_is_printed_layout(self): self.what_is_printed_info.hide() self.what_is_printed_table.hide() def create_finish_print_layout(self): self.finish_print_layout = QVBoxLayout(self) self.finish_print_info = QLabel('Finish print: ', self) self.finish_print_info_font = QFont() self.finish_print_info_font.setPixelSize(16) self.finish_print_info_font.setBold(True) self.finish_print_info.setFont(self.finish_print_info_font) self.finish_print_layout.addWidget(self.finish_print_info) self.busy_printers_field = QListWidget(self) self.finish_print_layout.addWidget(self.busy_printers_field) self.finish_print_apply_button = QPushButton('Finish print', self) self.finish_print_apply_button.clicked.connect(self.finish_print_apply_button_trigger) self.finish_print_filo_layout = QHBoxLayout(self) self.finish_print_filo_layout_descriptions = QVBoxLayout(self) self.finish_print_filo_layout_select = QVBoxLayout(self) self.finish_print_filo_layout.addLayout(self.finish_print_filo_layout_descriptions) self.finish_print_filo_layout.addLayout(self.finish_print_filo_layout_select) self.finish_print_filo_manufacturer_description = QLabel('Filament manufacturer: ', self) self.finish_print_filo_diameter_description = QLabel('Filament diameter: ', self) self.finish_print_filo_type_description = QLabel('Filament type: ', self) self.finish_print_filo_color_description = QLabel('Filament color: ', self) self.finish_print_filo_amount_description = QLabel('Amount [gram]: ', self) self.finish_print_filo_layout_descriptions.addWidget(self.finish_print_filo_manufacturer_description) self.finish_print_filo_layout_descriptions.addWidget(self.finish_print_filo_diameter_description) self.finish_print_filo_layout_descriptions.addWidget(self.finish_print_filo_type_description) self.finish_print_filo_layout_descriptions.addWidget(self.finish_print_filo_color_description) self.finish_print_filo_layout_descriptions.addWidget(self.finish_print_filo_amount_description) self.finish_print_filo_manufacturer_select = QComboBox(self) self.finish_print_filo_diameter_select = QComboBox(self) self.finish_print_filo_type_select = QComboBox(self) self.finish_print_filo_color_select = QComboBox(self) self.finish_print_filo_amount_select = QLineEdit(self) self.finish_print_filo_layout_select.addWidget(self.finish_print_filo_manufacturer_select) self.finish_print_filo_layout_select.addWidget(self.finish_print_filo_diameter_select) self.finish_print_filo_layout_select.addWidget(self.finish_print_filo_type_select) self.finish_print_filo_layout_select.addWidget(self.finish_print_filo_color_select) self.finish_print_filo_layout_select.addWidget(self.finish_print_filo_amount_select) self.finish_print_layout.addLayout(self.finish_print_filo_layout) self.finish_print_layout.addWidget(self.finish_print_apply_button) self.main_layout.addLayout(self.finish_print_layout) self.hide_finish_print_layout() def find_filament_id(self, manufacturer, diameter, type, color): SQL_command = "select id FROM filament WHERE " + \ "manufacturer = '" + manufacturer + "' AND " + \ "diameter = " + diameter + " AND " + \ "color = '" + color + "' AND " + \ "type = '" + type + "'" cursor = self.db_connection.cursor() cursor.execute(SQL_command) res = cursor.fetchone() if res is not None: return res.id else: return -1 def update_finish_print_layout(self): self.busy_printers_field.clear() SQL_command = "SELECT printer_3d.id, manufacturer, model \ FROM printer_3d \ JOIN print_3d on printer_3d.id = print_3d.printer_id \ WHERE completion_date IS NULL AND printer_id IS NOT NULL" cursor = self.db_connection.cursor() cursor.execute(SQL_command) res = cursor.fetchone() while res is not None: self.busy_printers_field.addItem(str(res.id) + ', ' + res.manufacturer + ' ' + res.model) res = cursor.fetchone() #clearing all fields self.finish_print_filo_manufacturer_select.clear() self.finish_print_filo_diameter_select.clear() self.finish_print_filo_type_select.clear() self.finish_print_filo_color_select.clear() self.finish_print_filo_amount_select.clear() SQL_command = "SELECT DISTINCT manufacturer FROM filament" cursor = self.db_connection.cursor() cursor.execute(SQL_command) res = cursor.fetchone() while res is not None: self.finish_print_filo_manufacturer_select.addItem(res.manufacturer) res = cursor.fetchone() SQL_command = "SELECT DISTINCT diameter FROM filament" cursor = self.db_connection.cursor() cursor.execute(SQL_command) res = cursor.fetchone() while res is not None: self.finish_print_filo_diameter_select.addItem(str(res.diameter)) res = cursor.fetchone() SQL_command = "SELECT DISTINCT type FROM filament" cursor = self.db_connection.cursor() cursor.execute(SQL_command) res = cursor.fetchone() while res is not None: self.finish_print_filo_type_select.addItem(res.type) res = cursor.fetchone() SQL_command = "SELECT DISTINCT color FROM filament" cursor = self.db_connection.cursor() cursor.execute(SQL_command) res = cursor.fetchone() while res is not None: self.finish_print_filo_color_select.addItem(res.color) res = cursor.fetchone() def show_finish_print_layout(self): self.update_finish_print_layout() self.busy_printers_field.show() self.finish_print_info.show() self.finish_print_apply_button.show() self.finish_print_filo_manufacturer_description.show() self.finish_print_filo_diameter_description.show() self.finish_print_filo_type_description.show() self.finish_print_filo_color_description.show() self.finish_print_filo_manufacturer_select.show() self.finish_print_filo_diameter_select.show() self.finish_print_filo_type_select.show() self.finish_print_filo_color_select.show() self.finish_print_filo_amount_description.show() self.finish_print_filo_amount_select.show() def hide_finish_print_layout(self): self.busy_printers_field.hide() self.finish_print_info.hide() self.finish_print_apply_button.hide() self.finish_print_filo_manufacturer_description.hide() self.finish_print_filo_diameter_description.hide() self.finish_print_filo_type_description.hide() self.finish_print_filo_color_description.hide() self.finish_print_filo_manufacturer_select.hide() self.finish_print_filo_diameter_select.hide() self.finish_print_filo_type_select.hide() self.finish_print_filo_color_select.hide() self.finish_print_filo_amount_description.hide() self.finish_print_filo_amount_select.hide() def create_customer_leaderboards_layout(self): self.customer_leaderboards_layout = QVBoxLayout(self) self.customer_leaderboards_info = QLabel('Customer leaderboards: ', self) self.customer_leaderboards_info_font = QFont() self.customer_leaderboards_info_font.setPixelSize(16) self.customer_leaderboards_info_font.setBold(True) self.customer_leaderboards_info.setFont(self.customer_leaderboards_info_font) self.customer_leaderboards_layout.addWidget(self.customer_leaderboards_info) self.customer_leaderboards_table = QTableWidget(self) self.customer_leaderboards_layout.addWidget(self.customer_leaderboards_table) self.main_layout.addLayout(self.customer_leaderboards_layout) self.customer_leaderboards_table.setColumnCount(4) self.customer_leaderboards_table.setHorizontalHeaderLabels(['Username', 'First name', 'Last name', 'Loyalty points']) self.customer_leaderboards_layout.addWidget(self.customer_leaderboards_table) self.hide_customer_leaderboards_layout() def update_customer_leaderboards_layout(self): self.busy_printers_field.clear() SQL_command = "SELECT TOP 3 username, first_name, last_name, loyalty_points from customer order by loyalty_points DESC" cursor = self.db_connection.cursor() cursor.execute(SQL_command) res = cursor.fetchone() customers = [] while res is not None: customers.append(res) res = cursor.fetchone() self.customer_leaderboards_table.setRowCount(len(customers)) for i in range(0, len(customers)): self.customer_leaderboards_table.setItem(i, 0, QTableWidgetItem(customers[i].username)) self.customer_leaderboards_table.setItem(i, 1, QTableWidgetItem(customers[i].first_name)) self.customer_leaderboards_table.setItem(i, 2, QTableWidgetItem(customers[i].last_name)) self.customer_leaderboards_table.setItem(i, 3, QTableWidgetItem(str(customers[i].loyalty_points))) def show_customer_leaderboards_layout(self): self.update_customer_leaderboards_layout() self.customer_leaderboards_info.show() self.customer_leaderboards_table.show() def hide_customer_leaderboards_layout(self): self.customer_leaderboards_info.hide() self.customer_leaderboards_table.hide() def hide_all(self): self.hide_assign_print_layout() self.hide_what_is_printed_layout() self.hide_welcome_message_layout() self.hide_finish_print_layout() self.hide_customer_leaderboards_layout() self.hide_earnings_statistics_layout() def create_earnings_statistics_layout(self): self.earnings_statistics_layout = QVBoxLayout(self) self.main_layout.addLayout(self.earnings_statistics_layout) self.earnings_statistics_info = QLabel('Earnings Statistics: ', self) self.earnings_statistics_info_font = QFont() self.earnings_statistics_info_font.setPixelSize(16) self.earnings_statistics_info_font.setBold(True) self.earnings_statistics_info.setFont(self.earnings_statistics_info_font) self.earnings_statistics_layout.addWidget(self.earnings_statistics_info) self.earnings_statistics_selection_layout = QHBoxLayout(self) self.earnings_statistics_layout.addLayout(self.earnings_statistics_selection_layout) self.earnings_statistics_duration_info = QLabel('Statistics duration: ', self) self.earnings_statistics_duration_field = QComboBox(self) self.earnings_statistics_duration_field.addItem('1 Week') self.earnings_statistics_duration_field.addItem('1 Month') self.earnings_statistics_duration_field.addItem('1 Year') self.earnings_statistics_duration_field.currentIndexChanged.connect(self.update_earnings_plot) self.earnings_statistics_selection_layout.addWidget(self.earnings_statistics_duration_info) self.earnings_statistics_selection_layout.addWidget(self.earnings_statistics_duration_field) self.earnings_statistics_figure = Figure() self.earnings_statistics_canvas = FigureCanvas(self.earnings_statistics_figure) self.earnings_statistics_layout.addWidget(self.earnings_statistics_canvas) self.update_earnings_plot() self.hide_earnings_statistics_layout() def get_earnings_data_week(self): d = datetime.datetime.now() delta = datetime.timedelta(days=1, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) dates = [] earnings = [] xlabels = [] for i in range(0, 7): dates.append(str(d).split('.')[0]) d = d - delta xlabels.append(-i-1) for d in dates: SQL_command = "SELECT SUM(cost) FROM print_3d WHERE completion_date < '" + d + "';" cursor = self.db_connection.cursor() cursor.execute(SQL_command) res = cursor.fetchone() if res is not None: if res[0] is not None: earnings.append(res[0]) else: earnings.append(Decimal(0)) return xlabels, earnings def get_earnings_data_month(self): d = datetime.datetime.now() delta = datetime.timedelta(days=1, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) dates = [] earnings = [] xlabels = [] for i in range(0, 31): dates.append(str(d).split('.')[0]) d = d - delta xlabels.append(-i-1) for d in dates: SQL_command = "SELECT SUM(cost) FROM print_3d WHERE completion_date < '" + d + "';" cursor = self.db_connection.cursor() cursor.execute(SQL_command) res = cursor.fetchone() if res is not None: if res[0] is not None: earnings.append(res[0]) else: earnings.append(Decimal(0)) return xlabels, earnings def get_earnings_data_year(self): d = datetime.datetime.now() delta = relativedelta(months=1) dates = [] earnings = [] xlabels = [] for i in range(0, 12): dates.append(str(d).split('.')[0]) d = d - delta xlabels.append(-i-1) for d in dates: SQL_command = "SELECT SUM(cost) FROM print_3d WHERE completion_date < '" + d + "';" cursor = self.db_connection.cursor() cursor.execute(SQL_command) res = cursor.fetchone() if res is not None: if res[0] is not None: earnings.append(res[0]) else: earnings.append(Decimal(0)) return xlabels, earnings def update_earnings_plot(self): if (str(self.earnings_statistics_duration_field.currentText())) == '1 Week': ''' plot some random stuff ''' print('week') datax, datay = self.get_earnings_data_week() self.earnings_statistics_figure.clear() self.earnings_statiscitcs_subplot = self.earnings_statistics_figure.add_subplot(111) self.earnings_statiscitcs_subplot.clear() self.earnings_statiscitcs_subplot.grid(True) self.earnings_statiscitcs_subplot.set_xlabel('Day (from now)') self.earnings_statiscitcs_subplot.set_ylabel('Earnings [zl]') self.earnings_statiscitcs_subplot.plot(datax, datay, '*-') self.earnings_statistics_canvas.draw() if (str(self.earnings_statistics_duration_field.currentText())) == '1 Month': ''' plot some random stuff ''' print('month') # random data datax, datay = self.get_earnings_data_month() self.earnings_statistics_figure.clear() self.earnings_statiscitcs_subplot = self.earnings_statistics_figure.add_subplot(111) self.earnings_statiscitcs_subplot.clear() self.earnings_statiscitcs_subplot.grid(True) self.earnings_statiscitcs_subplot.set_xlabel('Day (from now)') self.earnings_statiscitcs_subplot.set_ylabel('Earnings [zl]') self.earnings_statiscitcs_subplot.plot(datax, datay, '*-') self.earnings_statistics_canvas.draw() if (str(self.earnings_statistics_duration_field.currentText())) == '1 Year': ''' plot some random stuff ''' datax, datay = self.get_earnings_data_year() self.earnings_statistics_figure.clear() self.earnings_statiscitcs_subplot = self.earnings_statistics_figure.add_subplot(111) self.earnings_statiscitcs_subplot.clear() self.earnings_statiscitcs_subplot.grid(True) self.earnings_statiscitcs_subplot.set_xlabel('Month (from now)') self.earnings_statiscitcs_subplot.set_ylabel('Earnings [zl]') print(self.earnings_statiscitcs_subplot.get_ylabel()) self.earnings_statiscitcs_subplot.plot(datax, datay, '*-') self.earnings_statistics_canvas.draw() def show_earnings_statistics_layout(self): self.earnings_statistics_info.show() self.earnings_statistics_duration_info.show() self.earnings_statistics_duration_field.show() self.earnings_statistics_canvas.show() def hide_earnings_statistics_layout(self): self.earnings_statistics_info.hide() self.earnings_statistics_duration_info.hide() self.earnings_statistics_duration_field.hide() self.earnings_statistics_canvas.hide() def earnings_statistics_button_trigger(self): self.hide_all() self.show_earnings_statistics_layout() def print_apply_button_trigger(self): if self.printer_field.currentItem() is not None: printer_id = self.printer_field.currentItem().text().split(',')[0] if self.print_field.currentItem() is not None: print_id = self.print_field.currentItem().text().split(',')[0] SQL_command = "UPDATE print_3d SET printer_id = " + \ printer_id + " WHERE print_3d.id = " + \ print_id cursor = self.db_connection.cursor() cursor.execute(SQL_command) cursor.commit() self.hide_assign_print_layout() self.show_assign_print_layout() popup = QMessageBox() popup.setIcon(QMessageBox.Information) popup.setText("Successfully assigned print to printer") popup.setWindowTitle("Assigned print to printer") popup.exec_() else: popup = QMessageBox() popup.setIcon(QMessageBox.Critical) popup.setText("Select print") popup.setWindowTitle("Error - print not selected") popup.exec_() else: popup = QMessageBox() popup.setIcon(QMessageBox.Critical) popup.setText("Select printer") popup.setWindowTitle("Error - printer not selected") popup.exec_() def assign_print_button_trigger(self): self.hide_all() self.show_assign_print_layout() def what_is_printed_button_trigger(self): self.hide_all() self.show_what_is_printed_layout() def finish_print_button_trigger(self): self.hide_all() self.show_finish_print_layout() def finish_print_apply_button_trigger(self): manufacturer = str(self.finish_print_filo_manufacturer_select.currentText()) diameter = str(self.finish_print_filo_diameter_select.currentText()) type = str(self.finish_print_filo_type_select.currentText()) color = str(self.finish_print_filo_color_select.currentText()) amount = str(self.finish_print_filo_amount_select.text()) if len(amount) != 0: amount = str((float(amount)) / 1000) filament_id = str(self.find_filament_id(manufacturer, diameter, type, color)) if filament_id == '-1': popup = QMessageBox() popup.setIcon(QMessageBox.Critical) popup.setText("There is no such filament") popup.setWindowTitle("No filament") popup.exec_() return date = str(datetime.datetime.now()).split('.')[0] if len(amount) == 0: popup = QMessageBox() popup.setIcon(QMessageBox.Critical) popup.setText("Please set amount of used filament") popup.setWindowTitle("No filament amount error") popup.exec_() return if self.busy_printers_field.currentItem() is not None: now = datetime.datetime.now() print_id = self.busy_printers_field.currentItem().text().split(',')[0] SQL_command = "UPDATE print_3d SET completion_date = '" + \ str(now)[0:10] + "' WHERE printer_id = " + \ print_id + "AND completion_date IS NULL" cursor = self.db_connection.cursor() cursor.execute(SQL_command) cursor.commit() self.hide_finish_print_layout() self.show_finish_print_layout() else: popup = QMessageBox() popup.setIcon(QMessageBox.Critical) popup.setText("Please select a printer") popup.setWindowTitle("No printer selected") popup.exec_() return SQL_command = "INSERT INTO filament_history (filament_id, order_date, delivered_date, added_amount) VALUES (" \ + filament_id + ", '" + date + "', '" + date + "', -" + amount + ')' cursor = self.db_connection.cursor() cursor.execute(SQL_command) cursor.commit() popup = QMessageBox() popup.setIcon(QMessageBox.Information) popup.setText("Successfully finished print") popup.setWindowTitle("Finished print") popup.exec_() def customer_leaderboards_button_trigger(self): self.hide_all() self.show_customer_leaderboards_layout() def logout_button_trigger(self): self.destroy() exit(0)
class mainwindow(QWidget): def __init__(self, fileName, parent=None): super(mainwindow, self).__init__(parent) self.zoom_count = 0 self.zoom_flag = False self.CSV_fileName = fileName self.zoom_file_path = "photo_edit/zoom/temp.jpg" widget = QWidget() self.mainLayout = QGridLayout(widget) self.btn_layout = QGridLayout(self) self.push_layout = QGridLayout() self.Qtree = QTreeView() # self.Qtree.setStyleSheet('QTreeView {background-color: purple; color: white; border:5px;' # 'border-style:outset;border-color: white;selection-color: yellow}') self.model = QtGui.QStandardItemModel(self) self.setWindowTitle("Main") self.setFixedSize(700, 550) self.Qtree.doubleClicked.connect(self.show_details) self.add_patient_pushbotton = QPushButton("Add New Patient") # self.add_patient_pushbotton.setStyleSheet('QPushButton {background-color:yellow;border-style:outset;' # 'border-width:5px;border-color: white}') self.add_patient_pushbotton.clicked.connect(self.add_patient) self.add_patient_pushbotton.setFixedSize(200, 30) self.zoom_in_push = QPushButton("Zoom In") # self.zoom_in_push.setStyleSheet('QPushButton {background-color:yellow;border-style:outset;' # 'border-width:2px;border-color: white}') self.zoom_in_push.clicked.connect(self.zoom) self.zoom_out_push = QPushButton("Zoom Out") # self.zoom_out_push.setStyleSheet('QPushButton {background-color:yellow;border-style:outset;' # 'border-width:2px;border-color: white}') self.zoom_out_push.clicked.connect(self.zoom) self.brightness_push = QPushButton("Brightness") # self.brightness_push.setStyleSheet('QPushButton {background-color:yellow;border-style:outset;' # 'border-width:2px;border-color: white}') self.brightness_push.clicked.connect(self.brightness) self.sharpness_push = QPushButton("Sharpness") # self.sharpness_push.setStyleSheet('QPushButton {background-color:yellow;border-style:outset;' # 'border-width:2px;border-color: white}') self.sharpness_push.clicked.connect(self.sharpness) self.color_push = QPushButton("Color") # self.color_push.setStyleSheet('QPushButton {background-color:yellow;border-style:outset;' # 'border-width:2px;border-color: white}') self.color_push.clicked.connect(self.color) self.reset_push = QPushButton("Reset") # self.reset_push.setStyleSheet('QPushButton {background-color:yellow;border-style:outset;' # 'border-width:2px;border-color: white}') self.reset_push.clicked.connect(self.reset) self.close_push = QPushButton("Close") # self.close_push.setStyleSheet('QPushButton {background-color:yellow;border-style:outset;' # 'border-width:2px;border-color: white}') self.close_push.clicked.connect(self.end) self.save_push = QPushButton("Add") # self.save_push.setStyleSheet('QPushButton {background-color:yellow;border-style:outset;' # 'border-width:2px;border-color: white}') self.save_push.clicked.connect(self.write_to_csv) self.save_push.setFixedSize(200, 30) self.back_push = QPushButton("Cancel") # self.back_push.setStyleSheet('QPushButton {background-color:yellow;border-style:outset;' # 'border-width:2px;border-color: white}') self.back_push.clicked.connect(self.loadCsv) self.back_push.setFixedSize(200, 30) self.back1_push = QPushButton("Back") # self.back1_push.setStyleSheet('QPushButton {background-color:yellow;border-style:outset;' # 'border-width:2px;border-color: white}') self.back1_push.clicked.connect(self.loadCsv) self.back1_push.setFixedSize(200, 30) self.save_push.hide() self.back_push.hide() self.back1_push.hide() self.name_edit_line = QLineEdit() self.name_edit_line.setFixedHeight(50) self.age_edit_line = QSpinBox() self.age_edit_line.setFixedHeight(50) self.date_edit_line = QLineEdit() self.date_edit_line.setFixedHeight(50) self.photo_edit_line = QLineEdit() self.photo_edit_line.setFixedHeight(50) self.diagnose_edit_line = QLineEdit() self.diagnose_edit_line.setFixedHeight(100) # self.diagnose_edit_line.setFixedSize(360, 100) self.Name_label = QLabel("Name:") # self.Name_label.setFixedHeight(20) self.Age_label = QLabel("Age:") self.Date_label = QLabel("visit Date:") self.photo_label = QLabel("Upload Photo:") self.diagnose_label = QLabel("Diagnose:") self.name_edit_line.hide() self.Name_label.hide() self.Age_label.hide() self.age_edit_line.hide() self.date_edit_line.hide() self.Date_label.hide() self.photo_edit_line.hide() self.photo_label.hide() self.diagnose_label.hide() self.diagnose_edit_line.hide() self.scroll = QScrollArea() self.scroll.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn) self.scroll.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn) self.scroll.setWidgetResizable(True) self.scroll.setWidget(widget) self.imageLabel = QLabel() self.listWidget = QListWidget(self) # self.listWidget.setStyleSheet('QListWidget{background-color: purple; color: white; border:5px;' # 'border-style:outset;border-color: white;selection-color: yellow}') self.listWidget.itemDoubleClicked.connect(self.image) self.listWidget.hide() self.Qtree.setModel(self.model) self.Qtree.hide() self.push_layout.addWidget(self.add_patient_pushbotton, 0, 0, 0, 1) self.push_layout.addWidget(self.zoom_in_push, 0, 0) self.push_layout.addWidget(self.zoom_out_push, 0, 1) self.push_layout.addWidget(self.brightness_push, 0, 2) self.push_layout.addWidget(self.sharpness_push, 0, 3) self.push_layout.addWidget(self.color_push, 0, 4) self.push_layout.addWidget(self.reset_push, 0, 5) self.push_layout.addWidget(self.close_push, 0, 6) self.push_layout.addWidget(self.save_push, 0, 0) self.push_layout.addWidget(self.back_push, 0, 1) self.push_layout.addWidget(self.back1_push, 0, 0) self.push_layout.addWidget(self.listWidget, 1, 0) self.btn_layout.addLayout(self.push_layout, 5, 0) self.btn_layout.addWidget(self.Name_label, 0, 0) self.btn_layout.addWidget(self.name_edit_line, 0, 1) self.btn_layout.addWidget(self.Age_label, 1, 0) self.btn_layout.addWidget(self.age_edit_line, 1, 1) self.btn_layout.addWidget(self.Date_label, 2, 0) self.btn_layout.addWidget(self.date_edit_line, 2, 1) self.btn_layout.addWidget(self.photo_label, 3, 0) self.btn_layout.addWidget(self.photo_edit_line, 3, 1) self.btn_layout.addWidget(self.diagnose_label, 4, 0) self.btn_layout.addWidget(self.diagnose_edit_line, 4, 1) self.btn_layout.addWidget(self.scroll) self.btn_layout.addWidget(self.Qtree, 0, 0) self.mainLayout.addWidget(self.imageLabel, 0, 0) self.scroll.hide() def loadCsv(self): self.model.clear() self.add_patient_pushbotton.show() self.back1_push.hide() self.listWidget.hide() self.name_edit_line.hide() self.Name_label.hide() self.Age_label.hide() self.age_edit_line.hide() self.date_edit_line.hide() self.Date_label.hide() self.photo_edit_line.hide() self.photo_label.hide() self.diagnose_label.hide() self.diagnose_edit_line.hide() self.save_push.hide() self.back_push.hide() self.zoom_out_push.hide() self.zoom_in_push.hide() self.close_push.hide() self.reset_push.hide() self.sharpness_push.hide() self.brightness_push.hide() self.color_push.hide() data = pd.read_csv(self.CSV_fileName) header = list(data) data = data.values.tolist() self.next_id = len(data) items = [QtGui.QStandardItem(str(l)) for l in header] self.model.appendRow(items) for lst in data: items = [QtGui.QStandardItem(str(l)) for l in lst] self.model.appendRow(items) self.Qtree.show() def show_details(self, signal): r = signal.row() - 1 if r >= 0: self.back1_push.show() self.listWidget.clear() data = pd.read_csv(self.CSV_fileName) data = data.values.tolist() self.d = data[r] txt = "id is: " + str(self.d[0]) + "\nname is: " + str(self.d[1]) + "\nage is: " + str( self.d[2]) + "\nDiagnoses: " + str( self.d[5]) \ + "\nPress to show the image" QListWidgetItem(txt, self.listWidget) self.listWidget.setGeometry(1, 1, 500, 200) self.Qtree.close() self.add_patient_pushbotton.hide() self.listWidget.show() else: pass def add_patient(self): self.Qtree.close() self.add_patient_pushbotton.hide() self.name_edit_line.clear() self.age_edit_line.clear() self.date_edit_line.clear() self.photo_edit_line.clear() self.diagnose_edit_line.clear() self.name_edit_line.show() self.Name_label.show() self.Age_label.show() self.age_edit_line.show() self.date_edit_line.show() self.Date_label.show() self.photo_edit_line.show() self.photo_label.show() self.diagnose_label.show() self.diagnose_edit_line.show() self.save_push.show() self.back_push.show() currentDT = datetime.datetime.now() self.date_edit_line.setText(str(currentDT)) def write_to_csv(self): name = self.name_edit_line.text() age = str(self.age_edit_line.value()) date = self.date_edit_line.text() image_name = "data/" + name + "_" + date + ".jpg" diag = self.diagnose_edit_line.text() l2 = [self.next_id, name, age, date, image_name, diag] data = pd.read_csv(self.CSV_fileName) header = list(data) l1 = data.values.tolist() dict = {} for i, key in enumerate(header): lst = [] for l in l1: lst.append(l[i]) lst.append(l2[i]) dict[str(key)] = lst df = pd.DataFrame(dict) df.to_csv(self.CSV_fileName, index=False) self.loadCsv() def image(self): self.scroll.show() self.listWidget.close() self.back1_push.hide() self.fileName_edit = "photo_edit/temp.jpg" try: image = Image.open(self.d[4]) image.save("photo_edit/temp.jpg") # self.scaleFactor = 0.0 self.scaleFactor = 1.0 fileName = self.d[4] if fileName: image = QtGui.QImage(fileName) # print(type(image)) if image.isNull(): QMessageBox.information(self, "Image Viewer", "Cannot load %s." % fileName) return self.qpixmap = QtGui.QPixmap.fromImage(image) self.imageLabel.setPixmap(self.qpixmap) self.imageLabel.show() except: # img = np.zeros((500,500,3)) # image = QtGui.QImage(img, img.shape[1],img.shape[0], img.shape[1] * 3, QtGui.QImage.Format_RGB888) img = Image.new('RGB', (700, 600), (0, 0, 0)) draw = ImageDraw.Draw(img) draw.text((200, 200), "No Photo To Display!", fill='rgb(255, 255, 255)', font=ImageFont.truetype( "/usr/share/fonts/dejavu/DejaVuSans.ttf", 25)) img.save(self.fileName_edit) img.save(self.d[4]) img = img.convert("RGBA") data = img.tobytes("raw", "RGBA") qim = QtGui.QImage(data, img.size[0], img.size[1], QtGui.QImage.Format_ARGB32) pix = QtGui.QPixmap.fromImage(qim) self.imageLabel.setPixmap(pix) self.imageLabel.show() self.add_patient_pushbotton.hide() self.zoom_out_push.show() self.zoom_in_push.show() self.close_push.show() self.reset_push.show() self.sharpness_push.show() self.brightness_push.show() self.color_push.show() def adjustScrollBar(self, scrollBar, scale): scrollBar.setValue( int(scale * scrollBar.value() + ((scale - 1) * scrollBar.pageStep() / 2))) def zoom(self): if "zoom" not in os.listdir("photo_edit"): os.mkdir("photo_edit/zoom") sender = self.sender() self.zoom_flag = True image = Image.open(self.fileName_edit) if sender == self.zoom_in_push: self.zoom_count += 1 else: self.zoom_count += -1 scale = 1.2 scale = (scale)**self.zoom_count self.adjustScrollBar(self.scroll.horizontalScrollBar(), scale) self.adjustScrollBar(self.scroll.verticalScrollBar(), scale) h = int(image.size[1] * scale) w = int(image.size[0] * scale) image = image.resize((w, h), Image.BICUBIC) image.save(self.zoom_file_path) self.imageLabel.clear() image = QtGui.QImage(self.zoom_file_path) self.qpixmap = QtGui.QPixmap.fromImage(image) self.imageLabel.setPixmap(self.qpixmap) def brightness(self): if self.zoom_flag: shutil.copy(self.zoom_file_path, self.fileName_edit) self.zoom_flag = False self.zoom_count = 0 image = Image.open(self.fileName_edit) enhancer = ImageEnhance.Contrast(image) out = enhancer.enhance(1.7) out.save(self.fileName_edit) out = QtGui.QImage(self.fileName_edit) self.imageLabel.clear() qpixmap = QtGui.QPixmap.fromImage(out) self.imageLabel.setPixmap(qpixmap) self.scaleFactor = 1.0 self.imageLabel.adjustSize() def sharpness(self): if self.zoom_flag: shutil.copy(self.zoom_file_path, self.fileName_edit) self.zoom_flag = False self.zoom_count = 0 self.image = Image.open(self.fileName_edit) enhancer = ImageEnhance.Sharpness(self.image) out = enhancer.enhance(1.7) out.save(self.fileName_edit) out = QtGui.QImage(self.fileName_edit) self.imageLabel.clear() qpixmap = QtGui.QPixmap.fromImage(out) self.imageLabel.setPixmap(qpixmap) self.scaleFactor = 1.0 self.imageLabel.adjustSize() def color(self): if self.zoom_flag: shutil.copy(self.zoom_file_path, self.fileName_edit) self.zoom_flag = False self.zoom_count = 0 self.image = Image.open(self.fileName_edit) enhancer = ImageEnhance.Color(self.image) out = enhancer.enhance(1.7) out.save(self.fileName_edit) out = QtGui.QImage(self.fileName_edit) self.imageLabel.clear() qpixmap = QtGui.QPixmap.fromImage(out) self.imageLabel.setPixmap(qpixmap) self.scaleFactor = 1.0 self.imageLabel.adjustSize() def reset(self): self.zoom_flag = False self.zoom_count = 0 self.imageLabel.clear() o_i = QtGui.QImage(self.d[4]) qpixmap = QtGui.QPixmap.fromImage(o_i) self.imageLabel.setPixmap(qpixmap) self.imageLabel.adjustSize() self.image = Image.open(self.d[4]) self.image.save("photo_edit/temp.jpg") def end(self): self.scroll.hide() self.imageLabel.close() self.loadCsv()
class ErrorsWidget(QDialog): ############################################################################### # ERRORS WIDGET SIGNALS ############################################################################### """ pep8Activated(bool) lintActivated(bool) """ pep8Activated = pyqtSignal(bool) lintActivated = pyqtSignal(bool) dockedWidget = pyqtSignal("QObject*") undockedWidget = pyqtSignal() changeTitle = pyqtSignal(str) ############################################################################### def __init__(self, parent=None): super(ErrorsWidget, self).__init__(parent, Qt.WindowStaysOnTopHint) self.pep8 = None self._outRefresh = True vbox = QVBoxLayout(self) self.listErrors = QListWidget() self.listErrors.setSortingEnabled(True) self.listPep8 = QListWidget() self.listPep8.setSortingEnabled(True) hbox_lint = QHBoxLayout() if settings.FIND_ERRORS: self.btn_lint_activate = QPushButton(self.tr("Lint: ON")) else: self.btn_lint_activate = QPushButton(self.tr("Lint: OFF")) self.errorsLabel = QLabel(self.tr("Static Errors: %s") % 0) hbox_lint.addWidget(self.errorsLabel) hbox_lint.addSpacerItem(QSpacerItem(1, 0, QSizePolicy.Expanding)) hbox_lint.addWidget(self.btn_lint_activate) vbox.addLayout(hbox_lint) vbox.addWidget(self.listErrors) hbox_pep8 = QHBoxLayout() if settings.CHECK_STYLE: self.btn_pep8_activate = QPushButton(self.tr("PEP8: ON")) else: self.btn_pep8_activate = QPushButton(self.tr("PEP8: OFF")) self.pep8Label = QLabel(self.tr("PEP8 Errors: %s") % 0) hbox_pep8.addWidget(self.pep8Label) hbox_pep8.addSpacerItem(QSpacerItem(1, 0, QSizePolicy.Expanding)) hbox_pep8.addWidget(self.btn_pep8_activate) vbox.addLayout(hbox_pep8) vbox.addWidget(self.listPep8) self.listErrors.itemClicked['QListWidgetItem*'].connect( self.errors_selected) # self.listErrors.itemActivated['QListWidgetItem*'].connect(self.errors_selected) self.listPep8.itemClicked['QListWidgetItem*'].connect( self.pep8_selected) # self.listPep8.itemActivated['QListWidgetItem*'].connect(self.pep8_selected) self.btn_lint_activate.clicked['bool'].connect(self._turn_on_off_lint) self.btn_pep8_activate.clicked['bool'].connect(self._turn_on_off_pep8) IDE.register_service('tab_errors', self) ExplorerContainer.register_tab(translations.TR_TAB_ERRORS, self) def install_tab(self): ide = IDE.getInstance() ide.goingDown.connect(self.close) def _turn_on_off_lint(self): """Change the status of the lint checker state.""" settings.FIND_ERRORS = not settings.FIND_ERRORS if settings.FIND_ERRORS: self.btn_lint_activate.setText(self.tr("Lint: ON")) self.listErrors.show() else: self.btn_lint_activate.setText(self.tr("Lint: OFF")) self.listErrors.hide() self.lintActivated.emit(settings.FIND_ERRORS) def _turn_on_off_pep8(self): """Change the status of the lint checker state.""" settings.CHECK_STYLE = not settings.CHECK_STYLE if settings.CHECK_STYLE: self.btn_pep8_activate.setText(self.tr("PEP8: ON")) self.listPep8.show() else: self.btn_pep8_activate.setText(self.tr("PEP8: OFF")) self.listPep8.hide() self.pep8Activated.emit(settings.CHECK_STYLE) def errors_selected(self): main_container = IDE.get_service('main_container') if main_container: editorWidget = main_container.get_current_editor() if editorWidget and self._outRefresh: lineno = int(self.listErrors.currentItem().data(Qt.UserRole)) editorWidget.jump_to_line(lineno) editorWidget.setFocus() def pep8_selected(self): main_container = IDE.get_service('main_container') if main_container: editorWidget = main_container.get_current_editor() if editorWidget and self._outRefresh: lineno = int(self.listPep8.currentItem().data(Qt.UserRole)) editorWidget.jump_to_line(lineno) editorWidget.setFocus() def refresh_pep8_list(self, pep8): self._outRefresh = False self.listPep8.clear() for lineno in pep8: linenostr = 'L%s\t' % str(lineno + 1) for data in pep8[lineno]: item = QListWidgetItem(linenostr + data.split('\n')[0]) item.setToolTip(linenostr + data.split('\n')[0]) item.setData(Qt.UserRole, lineno) self.listPep8.addItem(item) self.pep8Label.setText(self.tr("PEP8 Errors: %s") % len(pep8)) self._outRefresh = True def refresh_error_list(self, errors): self._outRefresh = False self.listErrors.clear() for lineno in errors: linenostr = 'L%s\t' % str(lineno + 1) for data in errors[lineno]: item = QListWidgetItem(linenostr + data) item.setToolTip(linenostr + data) item.setData(Qt.UserRole, lineno) self.listErrors.addItem(item) self.errorsLabel.setText(self.tr("Static Errors: %s") % len(errors)) self._outRefresh = True def clear(self): """ Clear the widget """ self.listErrors.clear() self.listPep8.clear() def reject(self): if self.parent() is None: self.dockedWidget.emit(self) def closeEvent(self, event): self.dockedWidget.emit(self) event.ignore()
class CustomerWindow(QWidget): def __init__(self, db_connection, customer_name): super().__init__() self.customer_name = customer_name self.db_connection = db_connection self.create_window() def create_window(self): self.setGeometry(300, 300, 600, 300) #x, y, w, h self.setWindowTitle('3D Printers DB - Logged as: ') self.main_layout = QHBoxLayout(self) self.create_menu() self.menu_spacer = QSpacerItem(40, 10) self.main_layout.addItem(self.menu_spacer) self.create_welcome_message_layout() self.create_customer_profile_layout() self.create_order_history_layout() self.create_make_order_layout() def hide_all(self): self.hide_welcome_message_layout() self.hide_customer_profile_layout() self.hide_make_order_layout() self.hide_order_history_layout() def create_menu(self): self.menu = QVBoxLayout(self) self.login_description = QLabel('Logged in as: ' + self.customer_name, self) font = QFont() font.setPixelSize(20) font.setBold(True) self.login_description.setFont(font) self.make_order_btn = QPushButton('Make order', self) self.order_history_btn = QPushButton('Order history', self) self.profile_btn = QPushButton('Profile', self) self.logout_btn = QPushButton('Logout and exit', self) self.make_order_btn.clicked.connect(self.make_oder_button_trigger) self.order_history_btn.clicked.connect( self.order_history_button_trigger) self.profile_btn.clicked.connect(self.profile_button_trigger) self.logout_btn.clicked.connect(self.logout_button_trigger) self.menu.addWidget(self.login_description) self.menu.addWidget(self.make_order_btn) self.menu.addWidget(self.order_history_btn) self.menu.addWidget(self.profile_btn) self.menu.addWidget(self.logout_btn) self.menu.addStretch() self.main_layout.addLayout(self.menu) def create_welcome_message_layout(self): self.welcome_message_layout = QVBoxLayout(self) self.welcome_message_font = QFont() self.welcome_message_font.setPixelSize(12) self.welcome_message_text = 'Welcome in Printer DB application.\nUse menu ' \ 'located on the left site of window for navigation.' self.welcome_message = QLabel(self.welcome_message_text) self.welcome_message.setFont(self.welcome_message_font) self.welcome_message_layout.addWidget(self.welcome_message) self.welcome_message_layout.addStretch() self.main_layout.addLayout(self.welcome_message_layout) def hide_welcome_message_layout(self): self.welcome_message.hide() def show_welcome_message_layout(self): self.welcome_message.show() def create_customer_profile_layout(self): self.customer_profile_grid = QGridLayout() self.customer_profile_layout = QVBoxLayout() self.customer_profile_info = QLabel('Profile: ', self) self.customer_profile_info_font = QFont() self.customer_profile_info_font.setPixelSize(16) self.customer_profile_info_font.setBold(True) self.customer_profile_info.setFont(self.customer_profile_info_font) self.customer_profile_layout.addWidget(self.customer_profile_info) self.password_label = QLabel('Password:'******'First name:', self) self.first_name_field = QLineEdit(self) self.last_name_label = QLabel('Last name:', self) self.last_name_field = QLineEdit(self) self.phone_label = QLabel('Phone number:', self) self.phone_field = QLineEdit(self) self.address_label = QLabel('Address:', self) self.address_field = QLineEdit(self) self.city_label = QLabel('City:', self) self.city_field = QLineEdit(self) self.loyalty_points_label = QLabel('Loyalty points:', self) self.loyalty_points_field = QLabel('numa', self) self.profile_change_button = QPushButton('Apply', self) self.profile_change_button.clicked.connect( self.apply_profile_change_button_trigger) self.customer_profile_grid.addWidget(self.password_label, 0, 0) self.customer_profile_grid.addWidget(self.password_field, 0, 1) self.customer_profile_grid.addWidget(self.first_name_label, 1, 0) self.customer_profile_grid.addWidget(self.first_name_field, 1, 1) self.customer_profile_grid.addWidget(self.last_name_label, 2, 0) self.customer_profile_grid.addWidget(self.last_name_field, 2, 1) self.customer_profile_grid.addWidget(self.phone_label, 3, 0) self.customer_profile_grid.addWidget(self.phone_field, 3, 1) self.customer_profile_grid.addWidget(self.address_label, 4, 0) self.customer_profile_grid.addWidget(self.address_field, 4, 1) self.customer_profile_grid.addWidget(self.city_label, 5, 0) self.customer_profile_grid.addWidget(self.city_field, 5, 1) self.customer_profile_grid.addWidget(self.first_name_label, 6, 0) self.customer_profile_grid.addWidget(self.first_name_field, 6, 1) self.customer_profile_grid.addWidget(self.loyalty_points_label, 7, 0) self.customer_profile_grid.addWidget(self.loyalty_points_field, 7, 1) self.customer_profile_grid.addWidget(self.profile_change_button, 8, 1) self.customer_profile_layout.addLayout(self.customer_profile_grid) self.customer_profile_layout.addStretch() self.main_layout.addLayout(self.customer_profile_layout) self.hide_customer_profile_layout() def hide_customer_profile_layout(self): self.customer_profile_info.hide() self.password_label.hide() self.password_field.hide() self.first_name_label.hide() self.first_name_field.hide() self.last_name_label.hide() self.last_name_field.hide() self.phone_label.hide() self.phone_field.hide() self.address_label.hide() self.address_field.hide() self.city_label.hide() self.city_field.hide() self.loyalty_points_label.hide() self.loyalty_points_field.hide() self.profile_change_button.hide() def show_customer_profile_layout(self): self.update_customer_profile_layout() self.customer_profile_info.show() self.password_label.show() self.password_field.show() self.first_name_label.show() self.first_name_field.show() self.last_name_label.show() self.last_name_field.show() self.phone_label.show() self.phone_field.show() self.address_label.show() self.address_field.show() self.city_label.show() self.city_field.show() self.loyalty_points_label.show() self.loyalty_points_field.show() self.profile_change_button.show() def update_customer_profile_layout(self): SQL_command = "SELECT * FROM customer WHERE username = '******'" cursor = self.db_connection.cursor() cursor.execute(SQL_command) res = cursor.fetchone() self.first_name_field.setText(res.first_name) self.last_name_field.setText(res.last_name) self.phone_field.setText(res.phone) self.address_field.setText(res.address) self.city_field.setText(res.city) self.loyalty_points_field.setText(str(res.loyalty_points)) def create_make_order_layout(self): self.make_order_layout = QVBoxLayout(self) self.make_order_grid = QGridLayout() self.make_order_info = QLabel('Make an order: ', self) self.make_order_info_font = QFont() self.make_order_info_font.setPixelSize(16) self.make_order_info_font.setBold(True) self.make_order_info.setFont(self.customer_profile_info_font) self.make_order_layout.addWidget(self.make_order_info) self.due_date_label = QLabel('Due date:', self) self.due_date_field = QDateEdit(self) self.filename_label = QLabel('File: ', self) self.filename_field = QLineEdit(self) self.filament_type_label = QLabel('Filament type:', self) self.filament_type_field = QListWidget(self) self.filament_type_field.addItem('ABS') self.filament_type_field.addItem('PLA') self.filament_color_label = QLabel('Filament color:', self) self.filament_color_field = QListWidget(self) self.filament_color_field.addItem('red') self.filament_color_field.addItem('green') self.filament_color_field.addItem('blue') self.filament_color_field.addItem('black') self.filament_color_field.addItem('white') self.filament_color_field.addItem('yellow') self.filament_color_field.addItem('pink') self.make_order_apply_button = QPushButton('Make order', self) self.make_order_apply_button.clicked.connect( self.apply_make_order_button_trigger) self.make_order_grid.addWidget(self.due_date_label, 0, 0) self.make_order_grid.addWidget(self.due_date_field, 0, 1) self.make_order_grid.addWidget(self.filename_label, 1, 0) self.make_order_grid.addWidget(self.filename_field, 1, 1) self.make_order_grid.addWidget(self.filament_type_label, 2, 0) self.make_order_grid.addWidget(self.filament_type_field, 2, 1) self.make_order_grid.addWidget(self.filament_color_label, 3, 0) self.make_order_grid.addWidget(self.filament_color_field, 3, 1) self.make_order_grid.addWidget(self.make_order_apply_button, 4, 1) self.make_order_layout.addLayout(self.make_order_grid) self.make_order_layout.addStretch() self.main_layout.addLayout(self.make_order_layout) self.hide_make_order_layout() def hide_make_order_layout(self): self.make_order_info.hide() self.due_date_label.hide() self.due_date_field.hide() self.filename_label.hide() self.filename_field.hide() self.filament_type_label.hide() self.filament_type_field.hide() self.filament_color_label.hide() self.filament_color_field.hide() self.make_order_apply_button.hide() def show_make_order_layout(self): self.make_order_info.show() self.due_date_label.show() self.due_date_field.show() self.filename_label.show() self.filename_field.show() self.filament_type_label.show() self.filament_type_field.show() self.filament_color_label.show() self.filament_color_field.show() self.make_order_apply_button.show() def create_order_history_layout(self): self.order_history_layout = QVBoxLayout(self) self.order_history_info = QLabel('Order history: ', self) self.order_history_info_font = QFont() self.order_history_info_font.setPixelSize(16) self.order_history_info_font.setBold(True) self.order_history_info.setFont(self.customer_profile_info_font) self.order_history_layout.addWidget(self.order_history_info) self.order_history_table = QTableWidget(self) self.order_history_layout.addWidget(self.order_history_table) self.main_layout.addLayout(self.order_history_layout) self.order_history_table.setColumnCount(5) self.order_history_table.setHorizontalHeaderLabels([ 'Filename', 'Filament type', 'Filament color', 'Due date', 'Completed', 'Cost' ]) self.hide_order_history_layout() def hide_order_history_layout(self): self.order_history_info.hide() self.order_history_table.hide() def show_order_history_layout(self): self.update_order_history_layout() self.order_history_info.show() self.order_history_table.show() def update_order_history_layout(self): SQL_command = "SELECT stl_filename, filament_type, filament_color, due_date, completion_date, cost \ FROM customer JOIN print_3d ON customer.username = print_3d.customer_username \ WHERE customer.username = '******'" SQL_command += "ORDER BY due_date" cursor = self.db_connection.cursor() cursor.execute(SQL_command) res = cursor.fetchone() self.order_history = [] while res is not None: self.order_history.append(res) res = cursor.fetchone() self.order_history_table.setRowCount(len(self.order_history)) for i in range(0, len(self.order_history)): self.order_history_table.setItem( i, 0, QTableWidgetItem(self.order_history[i].stl_filename)) self.order_history_table.setItem( i, 1, QTableWidgetItem(self.order_history[i].filament_type)) self.order_history_table.setItem( i, 2, QTableWidgetItem(self.order_history[i].filament_color)) self.order_history_table.setItem( i, 3, QTableWidgetItem(str(self.order_history[i].due_date)[0:10])) if self.order_history[i].completion_date is not None: completion = 'Yes' else: completion = 'Not' self.order_history_table.setItem(i, 4, QTableWidgetItem(completion)) self.order_history_table.setItem( i, 5, QTableWidgetItem(str(self.order_history[i].cost))) def order_history_button_trigger(self): self.hide_all() self.show_order_history_layout() def make_oder_button_trigger(self): self.hide_all() self.show_make_order_layout() def apply_make_order_button_trigger(self): due_date = self.due_date_field.date() due_date = due_date.toPyDate() filename = self.filename_field.text() print_time = str(randint(0, 15)) + ':' + str(randint(0, 59)) print_cost = str(randint(0, 50)) if len(filename) == 0: popup = QMessageBox() popup.setIcon(QMessageBox.Critical) popup.setText("Please insert model filename") popup.setWindowTitle("Error - no modelname") popup.exec_() return if self.filament_type_field.currentItem() is None: popup = QMessageBox() popup.setIcon(QMessageBox.Critical) popup.setText("Please select filament type") popup.setWindowTitle("Error - no filament type") popup.exec_() return filament_type = self.filament_type_field.currentItem().text() if self.filament_color_field.currentItem() is None: popup = QMessageBox() popup.setIcon(QMessageBox.Critical) popup.setText("Please select filament color") popup.setWindowTitle("Error - no filament color") popup.exec_() return filament_color = self.filament_color_field.currentItem().text() SQL_command = "INSERT INTO print_3d (printer_id, customer_username, due_date, completion_date," \ " estimated_printing_time, stl_filename, cost, filament_type, filament_color) " \ "VALUES(NULL, '" SQL_command += self.customer_name + "', '" SQL_command += str(due_date) + "', NULL, '" SQL_command += print_time + "', '" SQL_command += filename + "', " SQL_command += print_cost + ", '" SQL_command += filament_type + "', '" SQL_command += filament_color + "');" cursor = self.db_connection.cursor() cursor.execute(SQL_command) self.db_connection.commit() popup = QMessageBox() popup.setIcon(QMessageBox.Information) popup.setText("Successfully made an order") popup.setWindowTitle("Order sent") popup.exec_() def profile_button_trigger(self): self.hide_all() self.show_customer_profile_layout() def apply_profile_change_button_trigger(self): change = False SQL_command = 'UPDATE customer SET ' if len(self.password_field.text()) != 0: password = self.password_field.text() m = hashlib.sha512() m.update(password.encode()) password_hash = m.hexdigest() SQL_command += "password_hash = '" SQL_command += password_hash + "', " if len(self.first_name_field.text()) != 0: SQL_command += "first_name = '" SQL_command += self.first_name_field.text() + "', " change = True if len(self.last_name_field.text()) != 0: SQL_command += "last_name = '" SQL_command += self.last_name_field.text() + "', " change = True if len(self.phone_field.text()) == 9: SQL_command += "phone = '" SQL_command += self.phone_field.text() + "', " change = True if len(self.address_field.text()) != 0: SQL_command += "address = '" SQL_command += self.address_field.text() + "', " change = True if len(self.city_field.text()) != 0: SQL_command += "city = '" SQL_command += self.city_field.text() + "', " change = True SQL_command = SQL_command[:-2] SQL_command += 'WHERE username = '******'" + self.customer_name + "'" if change == True: cursor = self.db_connection.cursor() cursor.execute(SQL_command) self.db_connection.commit() popup = QMessageBox() popup.setIcon(QMessageBox.Information) popup.setText("Successfully applied changes to profile") popup.setWindowTitle("Profile Updated") popup.exec_() def logout_button_trigger(self): self.destroy() exit(0)
class FileRenameWidget(QWidget): """ 给文件加后缀例子:(^[^\.]+) 替换成\1_26 """ class ReplaceTemplateWidget(QWidget): def __init__(self, parent=None, **kwargs): super().__init__(parent, **kwargs) def __init__(self, parent=None, **kwargs): super().__init__(parent, **kwargs) self.fileDir = "" self.fileDragList = [] self.fileList = [] self.filterRe = "" self.dirDeepSearch = False self.filterUseRe = False self.replaceUseRe = False self.fileDirLineEdit = FileOpenDirLineEdit() self.dirDeepSearchCheckBox = QCheckBox("递归搜素目录") self.filterReLineEdit = QLineEdit(minimumWidth=240) self.filterUseReCheckBox = QCheckBox("使用re") self.replaceTmpBtn = QPushButton("模板")#"<span style='color:blue'>模板</span>" self.replaceOldLineEdit = QLineEdit(minimumWidth=240) self.replaceNewLineEdit = QLineEdit(minimumWidth=240) self.replaceUseReCheckBox = QCheckBox("使用re") self.execButton = QPushButton("execute(执行)", maximumWidth=100) self.replacePromptLabel = QLabel() self.fileListText = DragLineTextEdit() gridLayout = GridLayout(self, contentsMargins=(10, 10, 10, 10), spacing=10) replaceLayout = HBoxLayout(contentsMargins=(0, 10, 10, 10), spacing=10, widgets=[self.replaceOldLineEdit, QLabel("替换成"), self.replaceNewLineEdit, self.replaceUseReCheckBox, self.replaceTmpBtn,LayStretch(1)]) glWidgets = [ [GLItem(QLabel("目录:"), 1, 2), GLItem(self.fileDirLineEdit, 1, 4), GLItem(self.dirDeepSearchCheckBox, 1, 2),GLItem(QWidget(), 1, -1)], [GLItem(QLabel("过滤字符串:"), 1, 2), GLItem(self.filterReLineEdit, 1, 3), GLItem(self.filterUseReCheckBox, 1, 2),GLItem(QWidget(), 1, 3)], [GLItem(QLabel("替换:"), 1, 2),GLItem(replaceLayout, 1, -1)], [GLItem(self.execButton, 1, 2), GLItem(self.replacePromptLabel, 1, -1)], [GLItem(self.fileListText, 1, -1)] ] gridLayout.addWidgets(glWidgets) self.replaceTmpWidget = QListWidget(self) self.replaceTmpList = [{"text":"添加后缀","name":"add_suffix"}] self.replaceTmpWidget.addItems(replaceTmp['text'] for replaceTmp in self.replaceTmpList) self.replaceTmpWidget.resize(100, 300) self.replaceTmpWidget.hide() # 注册事件 self.registerSignalConnect() def registerSignalConnect(self): self.fileDirLineEdit.textChanged.connect(self.fileDirChanged) # self.filterReLineEdit.textChanged.connect(self.filterReChanged) # 回车触发事件(只输入\,re.compile会报错) self.filterReLineEdit.returnPressed.connect(self.filterReConfirm) self.replaceNewLineEdit.returnPressed.connect(lambda : self._setAllFileList()) self.fileListText.dragSignal.connect(self.fileDrag) """ 复选框的三种状态: Qt.Checked:2, 组件没有被选中(默认) Qt.PartiallyChecked1:, 组件被半选中 Qt.Unchecked:0, 组件被选中 """ #当一个信号与多个槽函数关联时,槽函数按照建立连接时的顺序依次执行。(我测试过确实是,网上有些人说的不对) #self.filterUseReCheckBox.stateChanged.connect(lambda state: print("111111111")) #self.filterUseReCheckBox.stateChanged.connect(lambda state: print("222222222")) self.dirDeepSearchCheckBox.stateChanged.connect(lambda state: setattr(self, "dirDeepSearch", state > 0)) self.dirDeepSearchCheckBox.stateChanged.connect(lambda state: self._setFileList()) self.filterUseReCheckBox.stateChanged.connect(lambda state: setattr(self, "filterUseRe", state>0) ) self.filterUseReCheckBox.stateChanged.connect(lambda state: self._setFileList()) self.replaceUseReCheckBox.stateChanged.connect(lambda state: setattr(self, "replaceUseRe", state>0) ) self.replaceUseReCheckBox.stateChanged.connect(lambda state: self._setFileList()) self.execButton.clicked.connect(self.execButtonClicked) self.replaceTmpBtn.clicked.connect(self.replaceTmpBtnClicked) self.replaceTmpWidget.itemClicked.connect(self.replaceTmpClicked) def replaceTmpBtnClicked(self,*param): if self.replaceTmpWidget.isVisible(): self.replaceTmpWidget.hide() else: #获取纵坐标,obj.y(),包括框架。如果没有父控件是相对于桌面坐标。 self.replaceTmpWidget.move(self.width()-100, self.replaceTmpBtn.y()+ self.replaceTmpBtn.height()) self.replaceTmpWidget.show() self.replaceTmpWidget.raise_() def replaceTmpClicked(self,item): replaceTmp = self.replaceTmpList[self.replaceTmpWidget.currentRow()] if replaceTmp["name"] == "add_suffix": self.replaceOldLineEdit.setText(r"(^[^\.]+)") self.replaceNewLineEdit.setText(r"\1_26") self.replaceUseReCheckBox.setChecked(True) self.replaceTmpWidget.hide() def fileDrag(self, links): for link in links: #python集合的+=要求右边是是可迭代对象 #self.fileDragList += link self.fileDragList.append(link) self._setAllFileList() def _getReplacePrompt(self, fileList): if len(fileList) == 0: self.replacePromptLabel.setText("") else: _,fileName = os.path.split(fileList[0]) fmt = "<span style='color:#02AC03;font-size:18px;'>{}</span> 修改成:<span style='color:#02AC03;font-size:18px;'>{}</span>" if not self.replaceUseRe: self.replacePromptLabel.setText(fmt.format(fileName, fileName.replace(self.replaceOldLineEdit.text(), self.replaceNewLineEdit.text()))) else: self.replacePromptLabel.setText(fmt.format(fileName, re.sub(self.replaceOldLineEdit.text(), self.replaceNewLineEdit.text(), fileName) )) def _getAllFileList(self): if len(self.fileDragList) == 0: return self.fileList fileSet = set(self.fileList) fileList = [file for file in self.fileList] for file in self.fileDragList: if file in fileSet: continue fileList.append(file) fileSet.add(file) return fileList def _setAllFileList(self): fileList = self._getAllFileList() self._getReplacePrompt(fileList) self.fileListText.setPlainText("\n".join(fileList)) def execButtonClicked(self, *params): reply = QMessageBox.information(self, '提示', '确定要修改文件名吗?', QMessageBox.Ok | QMessageBox.No, QMessageBox.No) if reply != QMessageBox.Ok: return old = self.replaceOldLineEdit.text() new = self.replaceNewLineEdit.text() for dirname, filename in (os.path.split(path) for path in self._getAllFileList()): if not self.replaceUseRe: newname = filename.replace(old, new) else: newname = re.sub(old, new, filename) if filename != newname: os.rename(os.path.join(dirname, filename), os.path.join(dirname, newname)) self.fileDragList.clear() self._setFileList() def fileDirChanged(self, fileDir): self.fileDir = fileDir self._setFileList() def filterReChanged(self, filterRe): self.filterRe = filterRe self._setFileList() def filterReConfirm(self): self.filterRe = self.filterReLineEdit.text() self._setFileList() def _setFileList(self): self.fileList.clear() if not os.path.isdir(self.fileDir): return try: if self.filterUseRe: filterRe = re.compile(self.filterRe) except Exception as e: """如果输入\,re.compile会报错""" #打印堆栈信息 #traceback.print_exc() # 或者得到堆栈字符串信息 info = traceback.format_exc() print(info) return first = True for parent, dirnames, filenames in os.walk(self.fileDir): #只搜索一层 if not self.dirDeepSearch and not first: break first = False for filename in filenames: if self.filterUseRe: if filterRe.search(filename) is None: continue else: if self.filterRe not in filename: continue self.fileList.append(os.path.join(parent, filename)) # 路径和文件名连接构成完整路径 self._setAllFileList()
class MovieFrame(QWidget, GuiComponent): def __init__(self,parent=None, gui=None): super().__init__(parent) self.gui = gui self.gui.register_listener(self) self.initFrame() def initFrame(self): self.createWidgets() self.updateWidgets(Movie.get(7)) self.show() def createWidgets(self): grid = QGridLayout() fontTitle = QFont('Arial',20) fontInfo = QFont('Arial',8) imgPix = QPixmap('noPoster.jpg') self.lblImg = QLabel(self) self.lblImg.setFixedSize(300, 465) self.lblImg.setScaledContents(True) self.lblTitle = QLabel("*No Title*",self) self.lblImg.setPixmap(imgPix) self.lblScenarist = QLabel("Writer : -", self) self.lblDirector = QLabel("Director: -", self) self.lblActors = QLabel("Actor(s): -",self) self.lblRuntime = QLabel("Runtime: -",self) self.lblRate = QLabel("IMDb Rate: -",self) self.lblAwards = QLabel("Awards : -",self) self.lblCountry = QLabel("Country : -",self) self.lblRelease = QLabel("Release date : -",self) self.lblPlot = QLabel("Plot: -",self) self.lstFile = QListWidget(self) #Set font to labels self.lblTitle.setFont(fontTitle) self.lblScenarist.setFont(fontInfo) self.lblDirector.setFont(fontInfo) self.lblActors.setFont(fontInfo) self.lblRuntime.setFont(fontInfo) self.lblRate.setFont(fontInfo) self.lblAwards.setFont(fontInfo) self.lblCountry.setFont(fontInfo) self.lblRelease.setFont(fontInfo) self.lblPlot.setFont(fontInfo) self.lblTitle.setWordWrap(True) self.lblScenarist.setWordWrap(True) self.lblDirector.setWordWrap(True) self.lblActors.setWordWrap(True) self.lblRuntime.setWordWrap(True) self.lblRate.setWordWrap(True) self.lblAwards.setWordWrap(True) self.lblCountry.setWordWrap(True) self.lblRelease.setWordWrap(True) self.lblPlot.setWordWrap(True) btnLauchnFilm = QPushButton("Launch Film",self) grid.addWidget(self.lblImg, 1, 0, 8, 0) grid.addWidget(self.lblTitle,0, 0, 1, 2) grid.addWidget(self.lblScenarist,1,1) grid.addWidget(self.lblDirector,2,1) grid.addWidget(self.lblActors,3,1) grid.addWidget(self.lblRuntime,4,1) grid.addWidget(self.lblRate,5,1) grid.addWidget(self.lblAwards,6,1) grid.addWidget(self.lblCountry,7,1) grid.addWidget(self.lblRelease,8,1) grid.addWidget(self.lblPlot,9,0,1,2) grid.addWidget(self.lstFile,10,0,1,2) grid.addWidget(btnLauchnFilm,11,0,2,2) self.setLayout(grid) def updateWidgets(self,film): if film.poster is not None: poster = self.importPosterFilm(film.poster) else : poster = self.importPosterFilm() self.lblImg.setPixmap(poster) if film.name is not None: self.lblTitle.setText(film.name) else: self.lblTitle.setText("*no title*") if film.writer is not None: self.lblScenarist.setText("Scenarist: "+film.writer) else: self.lblScenarist.setText("Scenarist: -") if film.directors is not None: self.lblDirector.setText("Directors: "+film.directors) else: self.lblDirector.setText("Directors: -") if film.actors is not None: self.lblActors.setText("Actors :"+film.actors) else: self.lblActors.setText("Actors : -") if film.runtime is not None : self.lblRuntime.setText("Runtime: " + film.runtime) else: self.lblRuntime.setText("Runtime: -") if film.rate is not None: self.lblRate.setText("Rate IMDb: "+ film.rate) else: self.lblRate.setText("Rate IMDb: -") # if film.awards is not None: # self.lblAwards.setText("Awards: "+film.awards) # else: # self.lblAwards.setText("Awards: -") # if film.Country is not None: # self.lblCountry.setText("Country: "+film.Country) # else: # self.lblCountry.setText("Country: -") if film.release is not None: self.lblRelease.setText("Release: "+str(film.release)) else: self.lblRelease.setText("Release: -") if film.desc is not None: self.lblPlot.setText("Plot: "+film.desc) else: self.lblPlot.setText("Plot: -") if len(film.files) == 1: self.lstFile.hide() else: for file in film.files: self.lstFile.addItem("test") self.lstFile.show() def seeBtnClicked(self): pass def importPosterFilm(self, path=''): image = QImage() pixMap = QPixmap("noPoster.jpg") if path is '': return pixMap try: html = request.urlopen(path) data = html.read() flag = False image.loadFromData(data) pixMap = QPixmap(image) except request.URLError: # in case there isn't the internet or the url gives 404 error or bad url print("a problem with the connection or the url has occurred") return pixMap def handleAction(self, name, data): pass def requestAction(self, name): pass
class MovieWidget(GuiComponent): def __init__(self,parent=None): """ This widget displays the movie info of a movie. It's stored in the ComponentAreaWidget. :param parent: parent of the widget :type parent: QWidget """ super().__init__(parent) self.settings = QSettings() self.initFrame() def initFrame(self): self.createWidgets() self.show() def onShowFrame(self): self.emit(ShowSearch()) def createWidgets(self): grid = QGridLayout() headerLayout = QHBoxLayout() fontTitle = QFont('Arial',20) fontInfo = QFont('Arial',8) goBackIcon = qta.icon('fa.chevron-left', active='fa.chevron-left', color='white', color_active='white') self.lblImg = QPoster(self) #QLabel(self) self.lblImg.setFixedSize(300, 465) self.lblImg.setScaledContents(True) self.btnGoBack = QPushButton(goBackIcon,"Return",self) self.btnGoBack.setMaximumWidth(100) self.btnGoBack.clicked.connect(self.btnGoBackClicked) self.lblTitle = QLabel("<b>*No Title*</b>",self) self.lblTitle.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Expanding) headerLayout.addWidget(self.btnGoBack) headerLayout.addWidget(self.lblTitle) #self.lblImg.setPixmap(imgPix) self.lblScenarist = QLabel("<b>Writer : -</b>", self) self.lblDirector = QLabel("<b>Director: -</b>", self) self.lblActors = QLabel("<b>Actor(s): -</b>",self) self.lblRuntime = QLabel("<b>Runtime: -</b>",self) self.lblRate = QLabel("<b>IMDb Rate: -</b>",self) self.lblRelease = QLabel("<b>Release date : -</b>",self) self.lblPlot = QTextEdit("<b>Plot: -</b>", self) self.lblPlot.setReadOnly(True) self.lstFile = QListWidget(self) self.lstFile.setMinimumSize(600,100) #Set font to labels self.lblTitle.setFont(fontTitle) self.lblScenarist.setFont(fontInfo) self.lblDirector.setFont(fontInfo) self.lblActors.setFont(fontInfo) self.lblRuntime.setFont(fontInfo) self.lblRate.setFont(fontInfo) self.lblRelease.setFont(fontInfo) self.lblPlot.setFont(fontInfo) self.lblTitle.setWordWrap(True) self.lblScenarist.setWordWrap(True) self.lblDirector.setWordWrap(True) self.lblActors.setWordWrap(True) self.lblRuntime.setWordWrap(True) self.lblRate.setWordWrap(True) self.lblRelease.setWordWrap(True) self.btnLaunchFilm = QPushButton("Play Film",self) self.btnLaunchFilm.setMinimumWidth(200) self.btnLaunchFilm.clicked.connect(lambda : self.btnPlayFileClicked(file=None)) self.btnShowInDir = QPushButton("Show in Explorer") self.btnShowInDir.setMinimumWidth(200) self.btnShowInDir.clicked.connect(lambda: self.btnShowInDirClicked(file=None)) self.btnDeleteFile = QPushButton("Delete File from Database") self.btnDeleteFile.setMinimumWidth(200) self.btnDeleteFile.clicked.connect(lambda : self.btnDeleteFileClicked(file=None,item=None)) #this BoxLayout is used to put the button launch, show in explorer and delete File one the same line btnBoxlayout = QHBoxLayout() btnBoxlayout.addWidget(self.btnLaunchFilm) btnBoxlayout.addWidget(self.btnShowInDir) btnBoxlayout.addWidget(self.btnDeleteFile) grid.addLayout(headerLayout, 0, 0, 1, 2) grid.addWidget(self.lblImg, 1, 0, 6, 2) grid.addWidget(self.lblScenarist,1,1,1,1) grid.addWidget(self.lblDirector,2,1) grid.addWidget(self.lblActors,3,1) grid.addWidget(self.lblRuntime,4,1) grid.addWidget(self.lblRate,5,1) grid.addWidget(self.lblRelease,6,1) grid.addWidget(self.lblPlot, 7, 0, 1, 2) grid.addWidget(self.lstFile,9,0,1,2) grid.addLayout(btnBoxlayout,9,0,1,2) self.setLayout(grid) def updateWidgets(self,film): self.film = film self.lblImg.updateUrl(self.film.poster) if self.film.name is not None: self.lblTitle.setText(self.film.name) else: self.lblTitle.setText("<b>*no title*") if self.film.writer is not None: self.lblScenarist.setText("<b>Scenarist: </b>"+self.film.writer) else: self.lblScenarist.setText("<b>Scenarist: </b>-") if self.film.directors is not None: self.lblDirector.setText("<b>Directors: </b>"+self.film.directors) else: self.lblDirector.setText("<b>Directors: </b>-") if self.film.actors is not None: self.lblActors.setText("<b>Actors :</b> "+self.film.actors) else: self.lblActors.setText("<b>Actors : </b>-") if self.film.runtime is not None : self.lblRuntime.setText("<b>Runtime: </b>" + datetime.utcfromtimestamp(int(self.film.runtime)).strftime("%H:%M:%S")) else: self.lblRuntime.setText("<b>Runtime: </b>-") if self.film.rate is not None: self.lblRate.setText("<b>Rate IMDb: </b>"+ self.film.rate) else: self.lblRate.setText("<b>Rate IMDb: -</b>") if self.film.release is not None: self.lblRelease.setText("<b>Release: </b>"+str(self.film.release)) else: self.lblRelease.setText("<b>Release: </b>-") if self.film.desc is not None: self.lblPlot.setText("Plot: " + self.film.desc) else: self.lblPlot.setText("Plot: -") if len(self.film.files) == 1: self.lstFile.hide() self.btnLaunchFilm.show() self.btnShowInDir.show() self.btnDeleteFile.show() elif len(self.film.files) >= 1: self.lstFile.clear() #we clear the list just to be sure there isn't any items inside the list from another movie for file in self.film.files: item = QListWidgetItem(self.lstFile) itemW = FileWidget(self, file) item.setSizeHint(itemW.sizeHint()) self.lstFile.setItemWidget(item, itemW) itemW.btnPlayFile.clicked.connect(lambda ignore, x=file: self.btnPlayFileClicked(x)) itemW.btnShowInDir.clicked.connect(lambda ignore, x=file: self.btnShowInDirClicked(x)) itemW.btnDelete.clicked.connect(lambda ignore , x=file, y=item: self.btnDeleteFileClicked(file=x,item=y)) self.lstFile.show() self.btnLaunchFilm.hide() self.btnShowInDir.hide() self.btnDeleteFile.hide() elif len(self.film.files)==0: self.lstFile.hide() self.btnShowInDir.hide() self.btnDeleteFile.hide() self.btnLaunchFilm.hide() def btnGoBackClicked(self): self.gui.emit(ShowFrame(mawie.gui.components.QMovieListWidget.MovieListWidget.__name__)) def btnShowInDirClicked(self, file=None): path = None if file is not None and file.path is not None : path = file.path elif file is None and len(self.film.files) == 1 and self.film.files[0].path is not None : path = self.film.files[0].path if path is not None: if os.name.lower() == "nt": # because windows path = path.replace("/", "\\") if os.path.isfile(path): if platform.system() == "Windows": subprocess.Popen(r'explorer /select,"{}"'.format(path)) elif platform.system() == "Darwin": subprocess.call(["open", "-R", path]) else: subprocess.Popen(["xdg-open", os.path.dirname(path)]) else: self.displayErrorMessage("This file doesn't exist", "This file doesn't exist anymore, " "it has been deleted or moved in another folder") def btnPlayFileClicked(self, file=None): """ Play the movie in the MoviePlayer or in the default player of the client system :param file: the file we want to play :type film: file model """ defaultPlayer = self.settings.value("infomovie/player-default") path = None if file is not None and file.path is not None: path = file.path elif file is None and len(self.film.files) == 1 and self.film.files[0].path is not None : path = self.film.files[0].path if path is not None: if os.path.isfile(path): if defaultPlayer == 'false': moviePlayer = MoviePlayer(path=path) moviePlayer.exec_() else: if platform.system() == "Windows": os.startfile(path) elif platform.system() == "Darwin": subprocess.Popen(["open", path]) else: subprocess.Popen(["xdg-open", path]) else: self.displayErrorMessage("This file doesn't exist", "This file doesn't exist anymore, " "it has maybe been deleted or moved in an other folder") def btnDeleteFileClicked(self, file=None,item=None): """ Play the movie in the MoviePlayer or in the default player of the client system :param file: the file we want to play :type film: file model """ fileDel = None if file is None: fileDel = self.film.files[0] else: fileDel = file if item is not None: response = QMessageBox.question(self, "Delete file", "Delete the file from database ? it will not delete the file from your computer", QMessageBox.Yes | QMessageBox.Cancel) if response == QMessageBox.Yes: row = self.lstFile.row(item) self.lstFile.takeItem(row) if self.lstFile.count() is 1: self.lstFile.hide() self.btnLaunchFilm.show() self.btnDeleteFile.show() self.btnShowInDir.show() fileDel.delete() else: response = QMessageBox.question(self, "Delete the last file of the movie", "Delete the file and the <b>movie</b> from database ? it will not delete the movie from your computer", QMessageBox.Yes | QMessageBox.Cancel) if response == QMessageBox.Yes: fileDel.delete() self.film.delete() self.gui.emit(ShowFrame(mawie.gui.components.QMovieListWidget.MovieListWidget.__name__, data=Movie.query())) def handle(self,event): super().handle(event) if isinstance(event, ShowFrame) and event.frame == self.__class__.__name__: self.updateWidgets(event.data) #if isinstance(event, ShowFrame) and event.data is not None: #log.info("MOVIE INFO-- %s",event.data) #self.emit(ShowFrame(self)) #self.updateWidgets(event.data) def displayErrorMessage(self,title="-",text="-"): """ this method is used to display error message for example when a file doesn't exist anymore :param title: the title of the message box :param text: the text of the message box :type title: str :type text: str """ msgBox = QMessageBox() msgBox.setIcon(QMessageBox.Critical) msgBox.setWindowTitle(title) msgBox.setText(text) msgBox.setStandardButtons(QMessageBox.Ok) msgBox.exec()
class ErrorsWidget(QDialog): dockWidget = pyqtSignal('PyQt_PyObject') undockWidget = pyqtSignal('PyQt_PyObject') def __init__(self, parent=None): super().__init__(parent, Qt.WindowStaysOnTopHint) box = QVBoxLayout(self) box.setContentsMargins(0, 0, 0, 0) box.setSpacing(0) # PEP8 self._list_pep8 = QListWidget() self._list_pep8.setWordWrap(True) self._list_pep8.setSortingEnabled(True) hbox = QHBoxLayout() hbox.setContentsMargins(5, 3, 5, 3) if settings.CHECK_STYLE: self._btn_pep8 = QPushButton("PEP8: ON") else: self._btn_pep8 = QPushButton("PEP8: OFF") self._pep8_label = QLabel("PEP8 Errors: %s" % 0) hbox.addWidget(self._pep8_label) hbox.addSpacerItem(QSpacerItem(1, 0, QSizePolicy.Expanding)) hbox.addWidget(self._btn_pep8) box.addLayout(hbox) box.addWidget(self._list_pep8) # Connections self._list_pep8.clicked.connect(self.__on_pep8_item_selected) self._btn_pep8.clicked.connect(self._turn_on_off_pep8) # Register service IDE.register_service("tab_errors", self) # ExplorerContainer.register_tab(translations.TR_TAB_ERRORS, self) @pyqtSlot() def __on_pep8_item_selected(self): main_container = IDE.get_service("main_container") neditor = main_container.get_current_editor() if neditor is not None: lineno = self._list_pep8.currentItem().data(Qt.UserRole) neditor.go_to_line(lineno) neditor.setFocus() @pyqtSlot() def _turn_on_off_pep8(self): """Change the status of the lint checker state""" settings.CHECK_STYLE = not settings.CHECK_STYLE if settings.CHECK_STYLE: self._btn_pep8.setText("PEP8: ON") self._list_pep8.show() else: self._btn_pep8.setText("PEP8: OFF") self._list_pep8.hide() # TODO: emit a singal to main container def refresh_pep8_list(self, errors): self._list_pep8.clear() for lineno, message in errors.items(): lineno_str = 'L%s\t' % str(lineno + 1) item = QListWidgetItem(lineno_str + message.split('\n')[0]) item.setData(Qt.UserRole, lineno) self._list_pep8.addItem(item) self._pep8_label.setText("PEP8 Errors: %s" % len(errors)) def reject(self): if self.parent() is None: self.dockWidget.emit(self) def closeEvent(self, event): self.dockWidget.emit(self) event.ignore()
class WidgetList(QWidget): def __init__(self, parent=None): super().__init__(parent) self.id_dict: Dict[int, Tuple[List[str], int]] = {} self.item_dict: DefaultDict[str, Set[tuple]] = defaultdict(set) self._init_ui() def _init_ui(self): layout = QVBoxLayout(self) self.splitter = QSplitter(orientation=Qt.Vertical, parent=self) self.label = QLabel('Number of widgets (not calculated)') self.update_button = QPushButton('Update') self.widget_list = QTreeWidget(self) self.differ_list = QListWidget(self) self.search_widget = QWidget(self) self.search_line = QLineEdit(self.search_widget) self.search_tree = QTreeWidget(self.search_widget) self.widget_list.setHeaderLabels( ['Class name', 'Object name', 'Number of children', 'id']) self.search_tree.setHeaderLabels( ['Class name', 'Object name', 'Number of children', 'id']) s_layout = QVBoxLayout(self.search_widget) s_layout.addWidget(self.search_line) s_layout.addWidget(self.search_tree) layout.addWidget(self.label) layout.addWidget(self.update_button) layout.addWidget(self.splitter) self.splitter.addWidget(self.widget_list) self.splitter.addWidget(self.differ_list) self.splitter.addWidget(self.search_widget) self.update_button.clicked.connect(self.update_widget_list) self.search_line.editingFinished.connect(self._update_search_list) self.differ_list.hide() @pyqtSlot(name='updateSearchList') def _update_search_list(self): search: str = self.search_line.text().lower() self.search_tree.clear() for key, value in self.item_dict.items(): if key.lower().startswith(search): for name_list in value: TreeWidgetItem(self.search_tree, name_list) def update_widget_list(self): self.widget_list.clear() self.differ_list.clear() self.item_dict.clear() count = 0 new_id_dict: Dict[int, Tuple[list, int]] = {} for obj in QApplication.topLevelWidgets(): count += self._update_list(obj, self.widget_list, new_id_dict) self.widget_list.update() self.label.setText(f'Number of widgets = {count}') self.widget_list.sortByColumn(2, Qt.DescendingOrder) for value in self.id_dict.values(): QListWidgetItem(' '.join(value[0]), self.differ_list) self.id_dict = new_id_dict def _update_list(self, parent_obj: QObject, parent_node: QTreeWidget or QTreeWidgetItem, new_id_dict: Dict[int, Tuple[List[str], int]]): count = 0 for obj in parent_obj.children(): name_list = self._get_name_list(obj) item = TreeWidgetItem(parent_node, name_list) obj_count = 0 for o in obj.children(): obj_count += self._update_list(o, item, new_id_dict) item.setText(2, str(obj_count)) name_list[2] = str(obj_count) self.item_dict[str(obj.__class__.__name__)].add(tuple(name_list)) id_ = id(obj) new_id_dict[id_] = [item.text(i) for i in range(4)], obj_count _, prev_count = self.id_dict.pop(id_, (None, None)) if prev_count is None: fr = 1 elif prev_count + obj_count == 0: fr = 0 else: fr = abs(prev_count - obj_count) / (prev_count + obj_count) item.setBackground(3, get_color(fr)) count += 1 + obj_count return count @staticmethod def _get_name_list(obj: QObject): return [ str(obj.__class__.__name__), obj.objectName(), '', str(id(obj)) ]
class MainWindow(DATA[0], DATA[1]): def __init__(self): super().__init__() self.setupUi(self) self.scrollArea.hide() self.label_6.hide() self.pushButton.clicked.connect(self.iniciar_sesion) self.setWindowTitle("PrograPop") self.scrollArea_2.hide() self.label_tiempo = QLabel("20", self) self.label_tiempo.move(500, 300) self.label_tiempo.resize(100, 100) self.label_tiempo.setFont(QFont("SansSerif", 20)) self.label_tiempo.hide() self.song_name = None self.song = None self.salas = [{"name": "hola", "usuarios": [], "artistas": "None"}] self.a = 0 self.chat = QListWidget(self) self.chat.resize(1000, 300) self.chat.move(30, 370) self.chat.hide() def iniciar_sesion(self): self.name = self.lineEdit.text() self.usuario_back = BE_Client.Client_Back(self) time.sleep(2) self.usuario_back.get_salas() time.sleep(2) self.lineEdit.hide() self.label_2.hide() self.pushButton.hide() self.titulo.setText("Elige una Sala") self.lista_items = QListWidget(self) for item in self.salas: self.lista_items.addItem( "Sala : {}, Usuarios: {}, artistas: {}".format( item["name"], len(item["usuarios"]), item["artistas"])) self.lista_items.show() self.lista_items.resize(500, 200) self.lista_items.move(300, 200) self.lista_items.itemClicked.connect(self.conectarse_sala) self.actualizar = QPushButton("Actualizar", self) self.actualizar.move(1000, 100) self.actualizar.show() self.actualizar.clicked.connect(self.actualizar_salas) def conectarse_sala(self, item): self.lista_items.hide() name = item.text().split(",")[0].split(":")[1].replace(" ", "") self.sala_actual = name self.usuario_back.connect_sala(name) self.usuario_back.get_info() self.scrollArea.hide() self.titulo.setText(name) self.label_6.hide() self.actualizar.hide() self.volver = QPushButton("Salir", self) self.volver.move(30, 30) self.volver.clicked.connect(self.volver_menu) self.volver.show() # CHAT self.chat.show() self.chat.addItem("Chat") self.line_chat = QLineEdit(self) self.line_chat.move(40, 690) self.line_chat.resize(1000, 30) self.chatButton = QPushButton("Enviar", self) self.chatButton.move(1050, 690) self.chatButton.show() self.line_chat.show() self.chatButton.clicked.connect(self.enviar_mensaje) # Juego self.opcion1 = QPushButton("opcion1", self) self.opcion2 = QPushButton("opcion2", self) self.opcion3 = QPushButton("opcion3 ", self) self.opcion1.move(30, 200) self.opcion2.move(400, 200) self.opcion3.move(700, 200) self.opcion1.resize(200, 30) self.opcion2.resize(200, 30) self.opcion3.resize(200, 30) self.opcion1.show() self.opcion2.show() self.opcion3.show() self.opcion1.clicked.connect(self.opcion_selecta) self.opcion2.clicked.connect(self.opcion_selecta) self.opcion3.clicked.connect(self.opcion_selecta) while self.sala_actual != None: while not self.song_name: pass self.song = QSound(self.song_name) self.song_name = None self.song.play() self.label_tiempo.show() self.opcion1.show() self.opcion2.show() self.opcion3.show() QTest.qWait(1000) QTest.qWait(1000) self.label_tiempo.setText("19") QTest.qWait(1000) self.label_tiempo.setText("19") QTest.qWait(1000) self.label_tiempo.setText("17") QTest.qWait(1000) self.label_tiempo.setText("16") QTest.qWait(1000) self.label_tiempo.setText("15") QTest.qWait(1000) self.label_tiempo.setText("14") QTest.qWait(1000) self.label_tiempo.setText("13") QTest.qWait(1000) self.label_tiempo.setText("12") QTest.qWait(1000) self.label_tiempo.setText("11") QTest.qWait(1000) self.label_tiempo.setText("10") QTest.qWait(1000) self.label_tiempo.setText("9") QTest.qWait(1000) self.label_tiempo.setText("8") QTest.qWait(1000) self.label_tiempo.setText("7") QTest.qWait(1000) self.label_tiempo.setText("6") QTest.qWait(1000) self.label_tiempo.setText("5") QTest.qWait(1000) self.label_tiempo.setText("4") QTest.qWait(1000) self.label_tiempo.setText("3") QTest.qWait(1000) self.label_tiempo.setText("2") QTest.qWait(1000) self.label_tiempo.setText("1") QTest.qWait(1000) self.opcion1.hide() self.opcion2.hide() self.opcion3.hide() self.label_tiempo.hide() self.label_tiempo.setText("20") self.chat.addItem("Server: Preparate para la siguiente ronda") self.song.stop() QTest.qWait(1000) def actualizar_salas(self): self.lista_items.clear() self.usuario_back.get_salas() for item in self.salas: self.lista_items.addItem( "Sala : {}, Usuarios: {}, artistas: {}".format( item["name"], len(item["usuarios"]), item["artistas"])) def volver_menu(self): self.chat.clear() self.chat.hide() self.usuario_back.get_salas() time.sleep(0.2) self.usuario_back.disconnect_sala(self.sala_actual) time.sleep(0.2) self.usuario_back.get_info() time.sleep(0.2) self.sala_actual = None self.song.stop() self.titulo.setText("Elige una Sala") self.label_6.setText("Bienvenido {}\nTienes {} puntos".format( self.name, self.usuario_back.puntos)) self.label_6.show() self.label.setText("Nombre: {} - Usuarios : {} - Artistas : {}".format( self.salas[0]["name"], len(self.salas[0]["usuarios"]), self.salas[0]["artistas"])) self.lista_items.show() self.actualizar.show() self.volver.hide() self.line_chat.hide() self.chatButton.hide() self.scrollArea_2.hide() self.opcion1.hide() self.opcion2.hide() self.opcion3.hide() def enviar_mensaje(self): mensaje = self.line_chat.text() self.line_chat.setText("") self.usuario_back.chat(mensaje, self.sala_actual) def opcion_selecta(self): boton = self.sender() self.opcion1.hide() self.opcion2.hide() self.opcion3.hide() self.usuario_back.desicion(boton.text())
class ResumeBox(QGroupBox): restartRequested = pyqtSignal(QWidget) def __init__(self, parent): super(ResumeBox, self).__init__(parent) self.engine = None self.game = None self.parent = parent self.matches = [] self.initUI() def initUI(self): self.widgetLayout = QVBoxLayout(self) self.savedlist = QListWidget(self) self.savedlist.setSelectionMode( QAbstractItemView.SingleSelection) self.savedlist.hide() self.widgetLayout.addWidget(self.savedlist) self.buttonLayout = QHBoxLayout() self.widgetLayout.addLayout(self.buttonLayout) self.resumebutton = QPushButton(self) self.resumebutton.clicked.connect(self.resumeGame) self.resumebutton.hide() self.buttonLayout.addWidget(self.resumebutton) self.cancelbutton = QPushButton(self) self.cancelbutton.clicked.connect(self.deleteGame) self.cancelbutton.hide() self.buttonLayout.addWidget(self.cancelbutton) self.emptyLabel = QLabel(self) self.widgetLayout.addWidget(self.emptyLabel) self.retranslateUI() def retranslateUI(self): self.setTitle(i18n( "ResumeBox", 'Saved Games')) self.resumebutton.setText( i18n("ResumeBox", 'Resume')) self.cancelbutton.setText( i18n("ResumeBox", 'Cancel')) self.emptyLabel.setText(i18n( "ResumeBox", 'No matches to be resumed')) def changeGame(self, game): self.game = game self.engine = ResumeEngine(game) self.savedlist.clear() self.matches = [] candidates = self.engine.getCandidates() if not candidates: self.savedlist.hide() self.resumebutton.hide() self.cancelbutton.hide() self.emptyLabel.show() else: self.emptyLabel.hide() for idMatch, candidate in candidates.items(): self.matches.append(idMatch) savedtime = datetime.datetime.strptime( candidate['started'], "%Y-%m-%d %H:%M:%S.%f") strtime = savedtime.strftime("%Y-%m-%d %H:%M:%S") hours, remainder = divmod(int(candidate['elapsed']), 3600) minutes, seconds = divmod(remainder, 60) strelapsed = "{0:02}:{1:02}:{2:02}".format( hours, minutes, seconds) msg = i18n("ResumeBox", 'Saved on {}. Time played: {}').format(strtime, strelapsed) item = QListWidgetItem(msg, self.savedlist) playerlist = "" for player in candidate['players']: playerlist += "\n " + player item.setToolTip(i18n( "ResumeBox", "Players: {}").format(playerlist)) self.savedlist.addItem(item) self.savedlist.show() self.resumebutton.show() self.cancelbutton.show() def resumeGame(self): selected = self.savedlist.selectedIndexes() if len(selected) > 0: idMatch = self.matches[selected[0].row()] gameengine = self.engine.resume(idMatch) matchTab = GameWidgetFactory.resumeGameWidget( self.game, gameengine, self.parent) if matchTab: matchTab.closeRequested.connect(self.parent.removeTab) matchTab.restartRequested.connect(self.restartGame) self.parent.newTab(matchTab, self.game) def restartGame(self, gamewidget): self.restartRequested.emit(gamewidget) def deleteGame(self): selected = self.savedlist.selectedIndexes() if len(selected) > 0: idMatch = self.matches[selected[0].row()] tit = i18n("ResumeBox", 'Cancel Saved Game') msg = i18n("ResumeBox", "Are you sure you want to cancel saved game?") reply = QMessageBox.question(self, tit, msg, QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.No: return False gameengine = self.engine.resume(idMatch) gameengine.cancelMatch() self.changeGame(self.game)
class mainwindow(QWidget): def __init__(self, data_path, parent=None): super(mainwindow, self).__init__(parent) folders = os.listdir(data_path) self.mainLayout = QGridLayout(self) self.btn_layout = QGridLayout() self.buttons = [] for num, folder in enumerate(folders): i = num % 4 j = num // 4 folder_button = QPushButton(folder) self.buttons.append(folder_button) self.btn_layout.addWidget(folder_button, j, i) folder_button.setFixedSize(200, 30) folder_button.clicked.connect(partial(self.dispatcher, folder)) self.main_minue = QPushButton("back") self.btn_layout.addWidget(self.main_minue, 0, 0) self.main_minue.setFixedSize(200, 30) self.main_minue.hide() self.main_minue.clicked.connect(partial(self.main_layout, folder)) self.projectView = QTableView() self.mainLayout.addWidget(self.projectView, 1, 0) self.projectView.showMaximized() self.projectView.hide() self.listWidget = QListWidget(self) self.mainLayout.addWidget(self.listWidget, 1, 0) self.listWidget.hide() self.status_push = QPushButton("Status") self.btn_layout.addWidget(self.status_push, 0, 2) self.status_push.setFixedSize(200, 30) self.status_push.hide() self.search_push = QPushButton("Search") self.btn_layout.addWidget(self.search_push, 0, 1) self.search_push.setFixedSize(200, 30) self.search_push.hide() self.search_push.clicked.connect(partial(self.search_fn, folder)) self.search_counter = 0 txt = "please entre search text" self.search_lable = QLabel(txt) self.btn_layout.setContentsMargins(0, 0, 0, 0) self.btn_layout.addWidget(self.search_lable, 1, 0) self.search_lable.setFixedSize(200, 30) self.search_lable.hide() self.comboBox = QComboBox() self.comboBox.setObjectName(("comboBox")) self.btn_layout.addWidget(self.comboBox, 1, 2) self.comboBox.hide() self.search_line_edit = QLineEdit(self) self.btn_layout.addWidget(self.search_line_edit, 1, 1) self.search_line_edit.hide() self.search_line_edit.setFixedSize(200, 30) self.status_push.clicked.connect(self.show_status) self.back_push = QPushButton("Back") self.back_push.clicked.connect(partial(self.close_all, folder)) self.back_push.setFixedSize(200, 30) self.show_report = QPushButton("Show Report") self.show_report.clicked.connect(self.get_report) self.show_report.setFixedSize(200, 30) self.btn_layout.addWidget(self.back_push, 0, 0) self.btn_layout.addWidget(self.show_report, 0, 1) self.mainLayout.addLayout(self.btn_layout, 0, 0) self.back_push.hide() self.show_report.hide() self.setGeometry(0, 0, 1000, 1000) self.imageLabel = QLabel(self) self.imageLabel.hide() self.setWindowTitle("Stations") self.mainLayout.addWidget(self.imageLabel, 1, 0) def search_fn(self, folder): filename = main_path + "/" + folder + "/" + folder + ".xls" df = pd.read_excel(filename) header = list(df) for h in header: self.comboBox.addItem(h) if self.search_counter == 0: self.search_line_edit.show() self.comboBox.show() self.search_counter += 1 else: txt = self.search_line_edit.text() self.search_lable.hide() if txt == "": self.search_lable.show() else: self.search_counter = 2 df = df.replace(np.nan, '', regex=True) df = df.applymap(str) h = str(self.comboBox.currentText()) df1 = df[df[h].str.contains(txt)] tmp_filename = "tmp/tmp.csv" df1.to_csv(tmp_filename, index=False) self.show_table(tmp_filename) def main_layout(self, folder): if self.search_counter == 1: self.search_counter = 0 self.search_line_edit.hide() self.search_line_edit.setText("") self.search_lable.hide() self.comboBox.hide() elif self.search_counter == 2: self.dispatcher(folder) self.search_counter = 1 self.search_line_edit.setText("") else: self.setWindowTitle("Stations") self.projectView.hide() self.status_push.hide() self.search_push.hide() for folder in self.buttons: folder.show() self.main_minue.hide() def dispatcher(self, folder): filename = main_path + "/" + folder + "/" + folder + ".xls" # self.filename = filename self.setWindowTitle(folder + " Stations") self.show_table(filename) def show_status(self): labels = 'Done', 'half year target' sizes = [35, 65] explode = (0.1, 0.0) fig1, ax1 = plt.subplots() ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True, startangle=90) ax1.axis('equal') plt.show() def get_report(self): image_name = str(self.record[-1]) + ".jpg" if image_name in os.listdir("reports"): image_path = "reports" + "/" + image_name image = QtGui.QImage(image_path) self.qpixmap = QtGui.QPixmap.fromImage(image) self.imageLabel.setPixmap(self.qpixmap) else: img = Image.new('RGB', (700, 600), (0, 0, 0)) draw = ImageDraw.Draw(img) draw.text((60, 250), "No Photo To Display for station number " + str(self.record[-1]), fill='rgb(255, 255, 255)', font=ImageFont.truetype( "/usr/share/fonts/dejavu/DejaVuSans.ttf", 25)) img = img.convert("RGBA") data = img.tobytes("raw", "RGBA") qim = QtGui.QImage(data, img.size[0], img.size[1], QtGui.QImage.Format_ARGB32) pix = QtGui.QPixmap.fromImage(qim) self.imageLabel.setPixmap(pix) self.listWidget.clear() self.listWidget.close() self.show_report.hide() self.imageLabel.show() self.main_minue.hide() def show_table(self, filename): self.projectModel = PandasModel(filename) self.projectView.setModel(self.projectModel) self.projectView.doubleClicked.connect(self.show_details) self.projectView.show() self.status_push.show() self.search_push.show() self.main_minue.show() for folder in self.buttons: folder.hide() def show_details(self, clickedIndex): self.projectView.hide() self.status_push.hide() self.search_push.hide() self.search_line_edit.hide() self.search_lable.hide() self.comboBox.hide() self.main_minue.hide() df = self.projectModel._data header = list(df) self.record = df.values.tolist()[clickedIndex.row()] self.listWidget.clear() self.listWidget.show() self.back_push.show() self.show_report.show() txt = "" for h, d in zip(header, self.record): txt += str(h) + ": " + str(d) + "\n\n" it = QListWidgetItem(txt) font = QtGui.QFont() font.setBold(True) font.setWeight(200) font.setPointSize(12) it.setFont(font) it.setBackground(QtGui.QBrush(QtGui.QColor("lightblue"))) it.setTextAlignment(Qt.AlignRight) self.listWidget.addItem(it) def close_all(self, folder): self.search_line_edit.clear() self.search_counter = 0 self.listWidget.clear() self.listWidget.close() self.back_push.hide() self.show_report.hide() self.imageLabel.hide() filename = main_path + "/" + folder + "/" + folder + ".xls" self.show_table(filename)
class MiVentanasegundaria(QWidget): # Creamos una señal para manejar la respuesta del thread threads_response = pyqtSignal(object) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.init_gui() self.thread = None self.texto = Texto() def init_gui(self): # Configuramos los widgets de la interfaz self.resize(1500, 1000) self.label_1 = QLabel( "Bienvenido a Interaula, ingrese nombre de usuario y password", self) self.label_1.setFont(QFont("Sans Serif", 20)) self.label_1.move(350, 100) self.boton = QPushButton("Ingresar", self) self.boton.move(500, 650) self.label2 = QLabel("Usuario", self) self.label3 = QLabel("Password", self) self.label2.move(300, 400) self.label3.move(300, 450) self.user_line = QLineEdit(self) self.pass_line = QLineEdit(self) self.user_line.resize(200, 20) self.pass_line.resize(200, 20) self.user_line.move(400, 400) self.pass_line.move(400, 450) self.pass_line.setEchoMode(QLineEdit.Password) self.user_line.show() self.pass_line.show() self.imagen = QLabel("", self) self.imagen.move(20, 20) pixmap = QPixmap("misc/interaula.png") pixmap = pixmap.scaled(100, 100) self.imagen.setPixmap(pixmap) self.imagen.show() self.setWindowTitle('Interaula - Alumno') self.show() self.boton.clicked.connect(self.menu) def menu(self): self.usuario = Alumno(self.user_line.text(), self.pass_line.text()) QTest.qWait(500) if self.usuario.connected: self.label_1.setText("Bienvenido " + self.usuario.name) self.label2.hide() self.label3.hide() self.user_line.hide() self.pass_line.hide() self.boton.hide() ##### self.label2.setText( "Ingresa a un curso o inscribete en algun curso") self.label2.move(100, 200) ### Creamos tabla con los cursos disponibles self.tabla = QListWidget(self) self.tabla.addItem( "Sigla Nombre Curso Profesor " ) self.tabla.resize(700, 400) self.tabla.move(200, 200) i = 0 for item in self.usuario.clases: self.tabla.addItem( str(item[0]) + " " + str(item[1] + " " + str(item[2]))) self.tabla.itemClicked.connect(self.connect_curso) self.tabla.show() ### self.boton_crear = QPushButton("Inscribirse en Curso", self) self.boton_crear.move(500, 600) self.boton_crear.show() self.boton_crear.clicked.connect(self.inscribir_curso) else: self.label4 = QLabel( "Usuario o password incorrectos, intente nuevamente", self) self.label4.move(400, 730) self.label4.show() def cargar_clase(self): self.usuario.get_registro('1', self.curso_actual) self.registro = self.usuario.registro # Hideamos lo anterior ## Iniciamos el programa sin escucha self.diapos_totales = len([ f for f in listdir("1/") if isfile(join("1/", f)) and ".jpg" in f ]) self.imagen.hide() self.label_1.hide() self.lista_vivo.hide() # Configuramos los widgets de la interfaz self.diapositivas = QLabel("", self) # self.diapositivas.move() pixmap = QPixmap("1/1.jpg") pixmap = pixmap.scaled(650, 450) self.diapositivas.setPixmap(pixmap) self.diapositivas.show() self.diapositivas.move(100, 120) self.label = QLabel('Esperando inicio', self) self.label.setFont(QFont("Sans Serif", 25)) self.tabla = QListWidget(self) self.boton_3 = QPushButton("Siguiente", self) self.boton_3.move(400, 600) self.boton_4 = QPushButton("Anterior", self) self.boton_4.move(200, 600) self.tabla.show() self.boton_3.show() self.boton_4.show() self.boton_3.clicked.connect(self.siguiente) self.boton_4.clicked.connect(self.anterior) self.tabla.resize(400, 600) self.tabla.move(800, 100) self.label.resize(1000, 30) self.label.move(100, 50) self.boton.move(50, 700) self.resize(1500, 1000) self.diapo = 1 for i in self.registro[int(self.diapo - 1)]: self.tabla.addItem(i) def connect_curso(self, item): items = item.text().split( " ") self.label_1.setText("{}".format(items[1]).capitalize()) self.usuario.get_clases(items[0]) QTest.qWait(1000) self.curso_actual = items[0] self.usuario.buscar_vivo(self.curso_actual) QTest.qWait(500) self.label2.setText("Elija una clase pasada o alguna que este en vivo") self.label2.show() self.lista_vivo = QListWidget(self) self.lista_vivo.addItem("Clases en Vivo") for i in self.usuario.clases_vivo: self.lista_vivo.addItem("Sigla: {}, Numero de clase: {}".format( i[0], i[1])) self.lista_vivo.resize(300, 300) self.lista_vivo.move(500, 200) self.lista_vivo.show() self.lista_vivo.itemClicked.connect(self.empezar_clase) self.combo_box = QComboBox(self) for elemento in self.usuario.clases_actuales: self.combo_box.addItem(str(elemento[2])) self.combo_box.move(300, 300) self.combo_box.show() self.boton_cargar = QPushButton("Cargar Clase", self) self.boton_cargar.clicked.connect(self.cargar_clase) self.boton_cargar.move(300, 500) self.boton_cargar.show() self.boton_crear2 = QPushButton("Conectarse a Clase", self) self.boton_crear2.move(500, 500) self.boton_crear2.show() self.boton_crear.hide() self.tabla.hide() def inscribir_curso(self): self.dialog = QDialog() self.dialog.resize(500, 500) label1 = QLabel("Ingrese Sigla: ", self.dialog) label1.move(60, 100) self.line_edit1 = QLineEdit(self.dialog) self.line_edit1.move(230, 100) b1 = QPushButton("Inscribir", self.dialog) b1.move(300, 400) self.dialog.show() b1.clicked.connect(self.inscribir) def inscribir(self): self.usuario.inscribir_curso(self.line_edit1.text()) QTest.qWait(300) self.dialog.hide() self.menu() def empezar_clase(self, item): items = item.text().replace("Sigla: ", "").replace("Numero de clase: ", "").split(",") numero = str(int(items[1])) self.usuario.curso_actual = int(items[0]) self.imagen.hide() self.label_1.hide() ## Ajuste de señal self.senhal = self.usuario.senhal self.senhal.escribe_senhal.connect(self.update_labels) self.senhal2 = self.usuario.senhal2 self.senhal2.escribe_senhal.connect(self.siguiente) self.diapos_totales = len([ f for f in listdir(numero + "/") if isfile(join(numero + "/", f)) and ".jpg" in f ]) self.registro = [["Diapositiva {}".format(i)] for i in range(1, self.diapos_totales + 1)] self.lista_vivo.hide() # Configuramos los widgets de la interfaz self.diapositivas = QLabel("", self) # self.diapositivas.move() pixmap = QPixmap("1/1.jpg") pixmap = pixmap.scaled(650, 450) self.diapositivas.setPixmap(pixmap) self.diapositivas.show() self.diapositivas.move(100, 120) self.label = QLabel('Esperando inicio', self) self.label.setFont(QFont("Sans Serif", 25)) self.boton = QPushButton('Iniciar escucha', self) self.boton.clicked.connect(self.start_threads) self.tabla = QListWidget(self) self.tabla.addItem("Diapositiva 1") self.boton_2 = QPushButton("Guardar", self) self.boton_2.move(200, 700) self.boton_2.clicked.connect(self.guardar_archivo) self.boton_3 = QPushButton("Siguiente", self) self.boton_3.move(400, 600) self.boton_4 = QPushButton("Anterior", self) self.boton_4.move(200, 600) self.label.show() self.boton.show() self.tabla.show() self.boton_2.show() self.boton_3.show() self.boton_4.show() self.boton_3.clicked.connect(self.siguiente) self.boton_4.clicked.connect(self.anterior) self.tabla.resize(400, 600) self.tabla.move(800, 100) self.label.resize(1000, 30) self.label.move(100, 50) self.boton.move(50, 700) self.resize(1500, 1000) self.diapo = 1 # Conectamos la señal del thread al método que maneja self.threads_response.connect(self.update_labels) # Configuramos las propiedades de la ventana. def start_threads(self): if self.thread is None or not self.thread.is_alive(): self.thread = MiThread(self.threads_response, daemon=True) self.thread.start() def update_labels(self): mensaje = self.usuario.traduccion_actual print(mensaje) self.label.setText(mensaje) self.registro[self.diapo - 1].append(mensaje) self.tabla.addItem(mensaje) def guardar_archivo(self): self.thread.stop_thread() self.usuario.crear_clase(self.registro, self.curso_actual, self.clase_actual) def anterior(self): self.diapo -= 1 if self.diapo >= 1: self.tabla.clear() self.texto.back_diap() pixmap = QPixmap("1/{}.jpg".format(self.diapo)) pixmap = pixmap.scaled(650, 450) self.diapositivas.setPixmap(pixmap) for i in self.registro[int(self.diapo - 1)]: self.tabla.addItem(i) else: self.diapo += 1 def siguiente(self): self.diapo += 1 if self.diapo <= self.diapos_totales: self.tabla.clear() self.texto.back_diap() pixmap = QPixmap("1/{}.jpg".format(self.diapo)) pixmap = pixmap.scaled(650, 450) self.diapositivas.setPixmap(pixmap) for i in self.registro[int(self.diapo - 1)]: self.tabla.addItem(i) else: self.diapo -= 1
class Demo(QWidget): def __init__(self): super(Demo, self).__init__() self.time_label = QLabel(self) self.volume_slider = QSlider(self) self.progress_slider = QSlider(self) self.sound_btn = QPushButton(self) self.previous_btn = QPushButton(self) self.play_pause_btn = QPushButton(self) self.next_btn = QPushButton(self) self.mode_btn = QPushButton(self) self.list_btn = QPushButton(self) self.list_widget = QListWidget(self) self.h1_layout = QHBoxLayout() self.h2_layout = QHBoxLayout() self.all_v_layout = QVBoxLayout() self.playlist = QMediaPlaylist(self) self.player = QMediaPlayer(self) self.widget_init() self.layout_init() self.signal_init() def widget_init(self): self.time_label.setText('--/--') self.volume_slider.setRange(0, 100) self.volume_slider.setValue(100) self.volume_slider.setOrientation(Qt.Horizontal) self.progress_slider.setEnabled(False) self.progress_slider.setOrientation(Qt.Horizontal) self.sound_btn.setIcon(QIcon('images/sound_on.png')) self.previous_btn.setIcon(QIcon('images/previous.png')) self.play_pause_btn.setIcon(QIcon('images/play.png')) self.next_btn.setIcon(QIcon('images/next.png')) self.mode_btn.setIcon(QIcon('images/list_loop.png')) self.list_btn.setIcon(QIcon('images/show.png')) self.player.setPlaylist(self.playlist) self.media_list = ['/Users/louis/Downloads/music1.mp3', '/Users/louis/Downloads/music2.mp4', '/Users/louis/Downloads/music3.mp3'] for m in self.media_list: self.playlist.addMedia(QMediaContent(QUrl.fromLocalFile(m))) self.playlist.setPlaybackMode(QMediaPlaylist.Sequential) self.list_widget.addItems([m.split('/')[-1] for m in self.media_list]) def layout_init(self): self.h1_layout.addWidget(self.progress_slider) self.h1_layout.addWidget(self.time_label) self.h2_layout.addWidget(self.volume_slider) self.h2_layout.addWidget(self.sound_btn) self.h2_layout.addWidget(self.previous_btn) self.h2_layout.addWidget(self.play_pause_btn) self.h2_layout.addWidget(self.next_btn) self.h2_layout.addWidget(self.mode_btn) self.h2_layout.addWidget(self.list_btn) self.all_v_layout.addLayout(self.h1_layout) self.all_v_layout.addLayout(self.h2_layout) self.all_v_layout.addWidget(self.list_widget) self.all_v_layout.setSizeConstraint(QVBoxLayout.SetFixedSize) self.setLayout(self.all_v_layout) def signal_init(self): self.sound_btn.clicked.connect(lambda: self.btn_func(self.sound_btn)) self.previous_btn.clicked.connect(lambda: self.btn_func(self.previous_btn)) self.play_pause_btn.clicked.connect(lambda: self.btn_func(self.play_pause_btn)) self.next_btn.clicked.connect(lambda: self.btn_func(self.next_btn)) self.mode_btn.clicked.connect(lambda: self.btn_func(self.mode_btn)) self.list_btn.clicked.connect(lambda: self.btn_func(self.list_btn)) self.volume_slider.valueChanged.connect(self.volume_slider_func) self.list_widget.doubleClicked.connect(self.list_play_func) self.player.durationChanged.connect(self.get_duration_func) self.player.positionChanged.connect(self.get_position_func) self.progress_slider.sliderMoved.connect(self.update_position_func) def btn_func(self, btn): if btn == self.sound_btn: if self.player.isMuted(): self.player.setMuted(False) self.sound_btn.setIcon(QIcon('images/sound_on')) else: self.player.setMuted(True) self.sound_btn.setIcon(QIcon('images/sound_off')) elif btn == self.previous_btn: if self.playlist.currentIndex() == 0: self.playlist.setCurrentIndex(self.playlist.mediaCount() - 1) else: self.playlist.previous() elif btn == self.play_pause_btn: if self.player.state() == 1: self.player.pause() self.play_pause_btn.setIcon(QIcon('images/play.png')) else: self.player.play() self.play_pause_btn.setIcon(QIcon('images/pause.png')) elif btn == self.next_btn: if self.playlist.currentIndex() == self.playlist.mediaCount() - 1: self.playlist.setCurrentIndex(0) else: self.playlist.next() elif btn == self.mode_btn: if self.playlist.playbackMode() == 2: self.playlist.setPlaybackMode(QMediaPlaylist.Loop) self.mode_btn.setIcon(QIcon('images/item_loop.png')) elif self.playlist.playbackMode() == 3: self.playlist.setPlaybackMode(QMediaPlaylist.Random) self.mode_btn.setIcon(QIcon('images/random.png')) elif self.playlist.playbackMode() == 4: self.playlist.setPlaybackMode(QMediaPlaylist.Sequential) self.mode_btn.setIcon(QIcon('images/list_loop.png')) elif btn == self.list_btn: if self.list_widget.isHidden(): self.list_widget.show() self.list_btn.setIcon(QIcon('images/show.png')) else: self.list_widget.hide() self.list_btn.setIcon(QIcon('images/hide.png')) def volume_slider_func(self, value): self.player.setVolume(value) if value == 0: self.sound_btn.setIcon(QIcon('images/sound_off.png')) else: self.sound_btn.setIcon(QIcon('images/sound_on.png')) def list_play_func(self): self.playlist.setCurrentIndex(self.list_widget.currentRow()) self.player.play() self.play_pause_btn.setIcon(QIcon('images/pause.png')) def get_duration_func(self, d): self.progress_slider.setRange(0, d) self.progress_slider.setEnabled(True) self.get_time_func(d) def get_time_func(self, d): seconds = int(d / 1000) minutes = int(seconds / 60) seconds -= minutes * 60 if minutes == 0 and seconds == 0: self.time_label.setText('--/--') self.play_pause_btn.setIcon(QIcon('images/play.png')) else: self.time_label.setText('{}:{}'.format(minutes, seconds)) def get_position_func(self, p): self.progress_slider.setValue(p) def update_position_func(self, v): self.player.setPosition(v) d = self.progress_slider.maximum() - v self.get_time_func(d)
class SpyUI(QWidget): def __init__(self): super().__init__() self.spy = WeChatSpy(parser=parser, key=key) self.layout_main = QHBoxLayout(self) self.layout_left = QVBoxLayout(self) self.layout_middle = QVBoxLayout(self) self.layout_right = QVBoxLayout(self) self.layout_main.addLayout(self.layout_left) self.layout_main.addLayout(self.layout_middle) self.layout_main.addLayout(self.layout_right) self.label_profilephoto = QLabel(self) self.TE_contact_search = QTextEdit(self) self.LW_contact_search = QListWidget(self) self.TW_contact = QTabWidget(self) self.tab_friend = QListWidget() self.tab_group = QListWidget() self.tab_office = QListWidget() self.LW_chat_record = QListWidget(self) self.TE_send = SendTextEdit(self) self.CB_select_all_contact = QCheckBox("全选") self.CB_select_all_contact.setCheckState(Qt.Unchecked) self.setting_widget = SettingWidget(self) self.wxid = "" self.init_ui() def init_ui(self): fg = self.frameGeometry() center = QDesktopWidget().availableGeometry().center() fg.moveCenter(center) # 设置窗体 self.setting_widget.resize(300, 200) self.setting_widget.move(fg.topLeft()) self.setting_widget.hide() # 主窗体 self.resize(858, 608) self.move(fg.topLeft()) self.setWindowTitle("PyWeChatSpyUI Beta 1.3.3") # 设置登录信息头像 self.label_profilephoto.setFixedSize(32, 32) default_profilephoto = QPixmap("profilephotos/default.jpg").scaled( 32, 32) self.label_profilephoto.setPixmap(default_profilephoto) self.layout_left.addWidget(self.label_profilephoto) button_open_wechat = QPushButton(self) button_open_wechat.setText("打开\n微信") button_open_wechat.clicked.connect( lambda: self.spy.run(background=True)) button_open_wechat.setFixedSize(32, 32) button_settings = QPushButton(self) button_settings.setText("设置") button_settings.setFixedSize(32, 32) button_settings.clicked.connect(self.setting_widget.show) self.layout_left.addWidget(button_open_wechat) self.layout_left.addWidget(button_settings) # 联系人列表 self.TW_contact.currentChanged["int"].connect(self.tab_changed) self.TW_contact.addTab(self.tab_friend, "好友") self.TW_contact.addTab(self.tab_group, "群聊") self.TW_contact.addTab(self.tab_office, "公众号") self.tab_friend.itemClicked.connect(self.contact_clicked) self.tab_group.itemClicked.connect(self.contact_clicked) self.tab_office.itemClicked.connect(self.contact_clicked) self.TE_contact_search.setFixedSize(250, 24) self.TE_contact_search.textChanged.connect(self.search_contact) self.TE_contact_search.setPlaceholderText("搜索") self.LW_contact_search.setFixedSize(250, 200) self.LW_contact_search.itemClicked.connect(self.contact_search_clicked) self.layout_middle.addWidget(self.TE_contact_search) self.CB_select_all_contact.stateChanged[int].connect( self.contact_select_all) self.layout_middle.addWidget(self.CB_select_all_contact) self.layout_middle.addWidget(self.TW_contact) # 聊天区域 self.LW_chat_record.setFixedSize(468, 400) self.LW_chat_record.setContextMenuPolicy(3) self.LW_chat_record.customContextMenuRequested[QPoint].connect( self.rightMenuShow) self.layout_right.addWidget(self.LW_chat_record) layout = QHBoxLayout(self) button_file = QPushButton(self) button_file.setText("添加文件") button_file.clicked.connect(self.insert_file) layout.addWidget(button_file) self.layout_right.addLayout(layout) self.TE_send.setFixedSize(468, 100) self.layout_right.addWidget(self.TE_send) button_send = QPushButton(self) button_send.setText("发送") button_send.clicked.connect(self.send_msg) self.layout_right.addWidget(button_send) self.setLayout(self.layout_main) msg_thread = MsgThread() msg_thread.signal.connect(self.parser) msg_thread.start() self.show() self.LW_contact_search.raise_() self.LW_contact_search.move(self.TE_contact_search.x(), self.TE_contact_search.y() + 24) self.LW_contact_search.hide() def parser(self, data: dict): _type = data.pop("type") if _type == 1: # 登录成功 self.wxid = data["wxid"] profilephoto_path = f"profilephotos/{data['wxid']}.jpg" if not os.path.exists(profilephoto_path): if not download_image(data["profilephoto_url"], profilephoto_path): profilephoto_path = "profilephotos/default.jpg" profilephoto = QPixmap(profilephoto_path).scaled(32, 32) self.label_profilephoto.setPixmap(profilephoto) self.spy.query_contact_list() elif _type == 2: if profilephoto_url := data.get("profilephoto_url"): download_image(profilephoto_url, f"profilephotos/{data['wxid']}.jpg") if contact_need_details: wxid = contact_need_details.pop() self.spy.query_contact_details(wxid) else: self.refresh_contact_list() elif _type == 3: for contact in data["data"]: wxid_contact[contact["wxid"]] = contact if contact["wxid"] not in contact_filter: if not os.path.exists( f"profilephotos/{contact['wxid']}.jpg"): contact_need_details.append(contact["wxid"]) if contact["wxid"].endswith("chatroom"): GROUP_LIST.append(contact) elif contact["wxid"].startswith("gh_"): OFFICE_LIST.append(contact) else: FRIEND_LIST.append(contact) if data["total_page"] == data["current_page"]: self.refresh_contact_list() if contact_need_details: wxid = contact_need_details.pop() self.spy.query_contact_details(wxid)
class PhotoAlbum(QWidget): def __init__(self): super().__init__() self.left = 100 self.top = 100 self.width = 1600 self.height = 900 self.title = 'Photo Album' self.icon = 'icon.png' self.directory = os.getcwd() + '/images/' self.album = 'New Album' i = 0 while self.album in os.listdir(self.directory): i += 1 self.album = 'New Album (' + str(i) + ')' self.counter = 0 self.files = self.get_all_photo(self.directory) self.search_word = '' self.initUI() def initUI(self): self.setGeometry(self.left, self.top, self.width, self.height) self.setWindowTitle(self.title) self.setWindowIcon(QIcon(self.icon)) self.label = QLabel(self) self.label.setGeometry(50, 100, 900, 750) button_next = QPushButton('Next', self) button_next.move(120, 20) button_next.clicked.connect(self.go_next) button_previous = QPushButton('Previous', self) button_previous.move(20, 20) button_previous.clicked.connect(self.go_previous) button_change_directory = QPushButton('Change Directory', self) button_change_directory.move(250, 20) button_change_directory.clicked.connect(self.change_directory) button_delete = QPushButton('Delete', self) button_delete.move(400, 20) button_delete.clicked.connect(self.delete) self.line_name_of_photo = QLineEdit(self) self.line_name_of_photo.move(550, 20) button_add_to_current_album = QPushButton('Add to album', self) button_add_to_current_album.move(550, 60) button_add_to_current_album.clicked.connect(self.add_to_current_album) line_name_of_album = QLineEdit(self) line_name_of_album.move(700, 20) line_name_of_album.setText(self.album) line_name_of_album.textChanged[str].connect(self.get_new_name_of_album) button_create_new_album = QPushButton('Create a new album', self) button_create_new_album.move(700, 60) button_create_new_album.clicked.connect(self.create_new_album) button_short_look = QPushButton('Look Album', self) button_short_look.move(900, 50) button_short_look.clicked.connect(self.create_thumbnails) self.thumbnails_window = None self.list_of_files = QListWidget(self) self.list_of_files.addItems(self.files) self.list_of_files.resize(500, 200) self.list_of_files.move(1000, 600) self.list_of_files.itemClicked.connect(self.load_image_from_list) search_line = QLineEdit(self) search_line.move(1000, 200) search_line.textChanged[str].connect(self.get_new_search_word) self.search_parameter = QComboBox(self) self.search_parameter.addItem('Name') self.search_parameter.addItem('Year of creation') self.search_parameter.move(1000, 170) button_search = QPushButton('Search', self) button_search.move(1000, 230) button_search.clicked.connect(self.search) self.load_image() self.show() def search(self): new_files = [] if self.search_parameter.currentText() == 'Name': for file in self.files: temp_file_name = file.replace('\\', '/') if temp_file_name.split('/')[-1].find(self.search_word) != -1: new_files.append(file) elif self.search_parameter.currentText() == 'Year of creation': for file in self.files: print(self.search_word) print( datetime.fromtimestamp( os.path.getctime(file)).strftime('%Y')) if datetime.fromtimestamp(os.path.getctime(file)).strftime( '%Y') == self.search_word: new_files.append(file) self.files = new_files self.counter = 0 if len(self.files) == 0: self.list_of_files.hide() self.label.hide() self.line_name_of_photo.setText('') else: self.list_of_files.clear() self.list_of_files.addItems(self.files) self.list_of_files.show() self.load_image() self.label.show() def get_new_search_word(self, text): self.search_word = text def create_thumbnails(self): if not self.album in os.listdir('./images/'): return self.thumbnails_window = ThumbnailsWindow( self.album, self.get_all_photo('./images/' + self.album + '/', [])) self.thumbnails_window.show() def load_image_from_list(self): self.counter = self.list_of_files.currentRow() self.load_image() def get_new_name_of_album(self, text): self.album = text def create_new_album(self): if not self.album in os.listdir('./images/'): os.mkdir('./images/' + self.album) else: return def add_to_current_album(self): if not self.album in os.listdir('./images/'): return if len(self.files) == 0: return temp_file_name = self.files[self.counter].replace('\\', '/') shutil.copy(self.files[self.counter], './images/' + self.album) os.rename( './images/' + self.album + '/' + temp_file_name.split('/')[-1], './images/' + self.album + '/' + self.line_name_of_photo.text()) return def delete(self): if len(self.files) == 0: return else: self.files.remove(self.files[self.counter]) if len(self.files) == 0: self.label.hide() return else: self.counter = self.counter % len(self.files) self.load_image() def get_all_photo(self, directory, lisss=[]): for file in os.listdir(directory): file = os.path.join(directory, file) if os.path.isdir(file): self.get_all_photo(file, lisss) else: file_name, ext = os.path.splitext(file) if not (ext != '.jpg' and ext != '.png' and ext != '.gif') or os.path.isdir(file): lisss.append(file) return lisss def change_directory(self): directory = QFileDialog.getExistingDirectory(self) if directory == '': return self.directory = directory + '/' self.files = [] self.counter = 0 self.files = self.get_all_photo(self.directory, self.files) if len(self.files) == 0: self.list_of_files.hide() self.label.hide() self.line_name_of_photo.setText('') else: self.list_of_files.clear() self.list_of_files.addItems(self.files) self.list_of_files.show() self.load_image() self.label.show() def go_next(self): if len(self.files) == 0: return self.counter = (self.counter + 1) % len(self.files) self.load_image() def go_previous(self): if len(self.files) == 0: return self.counter = (self.counter - 1) % len(self.files) self.load_image() def keyPressEvent(self, e): key = e.key() if key == Qt.Key_Escape: self.close() def load_image(self): if len(self.files) == 0: return pixmap = QPixmap(self.files[self.counter]) while pixmap.width() > self.label.width() and pixmap.height( ) > self.label.height(): pixmap = pixmap.scaled(pixmap.width() // 2, pixmap.height() // 2) self.label.setPixmap(pixmap) temp_file_name = self.files[self.counter].replace('\\', '/') self.line_name_of_photo.setText(temp_file_name.split('/')[-1])
class App(QMainWindow): def __init__(self): super(App, self).__init__() self.title = "Deauthentication Attack" self.setWindowIcon(QtGui.QIcon('dtu.jpeg')) self.setupUI() self.setStyleSheet("""QToolTip { background-color: black; color: white; border: black solid 1px }""") def setupUI(self): global framecount setMonitorMode() self.setWindowTitle(self.title) self.setGeometry(50, 50, 650, 700) #BSSID for the AP for the attack self.textboxAP = QLineEdit(self) self.textboxAP.setPlaceholderText("Enter the target AP MAC address") self.textboxAP.move(20, 30) self.textboxAP.resize(280, 40) #Target of the attack (MAC address) self.textbox = QLineEdit(self) self.textbox.setPlaceholderText("Enter the target MAC address") self.textbox.move(20, 80) self.textbox.resize(280, 40) #Frame Amount line self.textbox_amount = QLineEdit(self) self.textbox_amount.setPlaceholderText("Enter amount of seconds") self.textbox_amount.move(20, 130) self.textbox_amount.resize(280, 50) ##channel for attack self.channeltextbox = QLineEdit(self) self.channeltextbox.setPlaceholderText( "Enter the channel for the attack") self.channeltextbox.move(20, 190) self.channeltextbox.resize(280, 50) ##ATTACK button self.attackbutton = QPushButton('ATTACK', self) self.attackbutton.setToolTip("Click to start the attack") self.attackbutton.resize(200, 50) self.attackbutton.move(350, 30) self.attackbutton.clicked.connect(self.on_attackclick) ##RESET BUTTON self.resetbutton = QPushButton('RESET', self) self.resetbutton.resize(200, 50) self.resetbutton.move(350, 100) self.resetbutton.clicked.connect(self.on_resetclick) self.resetbutton.setToolTip("Click to reset everything") ##SNIFF SSID/BSSID button self.sniffSSIDbutton = QPushButton('Sniff SSIDs', self) self.sniffSSIDbutton.resize(200, 50) self.sniffSSIDbutton.move(350, 170) self.sniffSSIDbutton.clicked.connect(self.on_ssidsniff) self.sniffSSIDbutton.setToolTip("Click to start sniffing for AP's") ##SNIFF STATION BUTTON self.sniffStationbutton = QPushButton('Sniff Stations', self) self.sniffStationbutton.hide() self.sniffStationbutton.resize(200, 50) self.sniffStationbutton.move(350, 240) self.sniffStationbutton.clicked.connect(self.on_stationsniff) self.sniffStationbutton.setToolTip( "Click to start sniffing for stations") #Stop sniffing button self.stopbutton = QPushButton('STOP', self) self.stopbutton.resize(200, 50) self.stopbutton.move(350, 310) self.stopbutton.clicked.connect(self.on_stopclick) self.stopbutton.setToolTip("Click to stop sniffing") #frame AMOUNT LABEL self.framelabel = QLabel( "Seconds : " + str(secondsCount) + "\n\n" + "Sent : " + str(framecount) + "\n" + "DeAuthentication Frames", self) self.framelabel.setFont(QtGui.QFont("Times", weight=QtGui.QFont.Bold)) self.framelabel.move(20, 230) self.framelabel.resize(270, 100) #QListWidget for SSID/BSSID self.sniffbox = QListWidget(self) self.sniffbox.setSelectionMode( QtWidgets.QAbstractItemView.SingleSelection) self.sniffbox.itemSelectionChanged.connect(self.on_sniffClick) self.sniffbox.move(20, 370) self.sniffbox.resize(600, 310) #QListWidget for the STA's self.sniffStationbox = QListWidget(self) self.sniffStationbox.setSelectionMode( QtWidgets.QAbstractItemView.SingleSelection) self.sniffStationbox.itemSelectionChanged.connect(self.on_stationClick) self.sniffStationbox.move(20, 370) self.sniffStationbox.resize(600, 310) self.sniffStationbox.hide() #author LABEL self.authorlabel = QLabel("v1.0 - Sebastian & Magnus", self) self.authorlabel.setFont(QtGui.QFont("Times", weight=QtGui.QFont.Bold)) self.authorlabel.move(200, 638) self.authorlabel.resize(270, 100) self.setFixedSize(self.size()) self.show() #@pyqtSlot() def on_sniffClick(self): if (len(self.sniffbox.selectedItems()) != 0): self.textboxAP.setText( (self.sniffbox.selectedItems()[0] ).text()[12:29]) # Substring : AP Mac adress self.channeltextbox.setText( (self.sniffbox.selectedItems()[0] ).text()[-2:].strip()) # Substring : AP channel def on_stationClick(self): if (len(self.sniffStationbox.selectedItems()) != 0): self.textbox.setText((self.sniffStationbox.selectedItems()[0] ).text()[15:32]) # Substring : AP Mac adress def checkifstop(self, frame): if breaksniff_flag == True: self.sniffbox.addItem("Sniffing stopped") self.sniffStationbox.addItem("Sniffing stopped") return "breaking" def FindSSIDtest(self, frame): global breaksniff_flag #we try a new channel every call, in an external thread moncheck = check_output( ["sudo", "iwconfig", "wlan0mon", "channel", str(channel_value)], stderr=subprocess.PIPE).decode("UTF-8") if frame.haslayer(Dot11): #der kunne bare stå haslayer(Dot11Beacon) if frame.type == 0 and frame.subtype == 8: #KUN beacon frames!! SSID = frame.info BSSID = frame.addr3.upper() #print(bssid) if (BSSID, SSID) not in ssid_bssid and len( SSID) != 0: #gider ikke hidden SSIDs aka 0 len. ssid_bssid.append((BSSID, SSID)) ch = int(ord(frame[Dot11Elt:3].info)) self.sniffbox.addItem("Found BSSID " + BSSID + " and SSID " + SSID + " on channel: " + str(ch)) #print(ssid_bssid) def FindSTAinSpecificBSSID(self, bssidsearch, frame, channel): global channel_enganged if channel_enganged == False: moncheck = check_output( ["sudo", "iwconfig", "wlan0mon", "channel", str(channel)], stderr=subprocess.PIPE).decode("UTF-8") channel_enganged = True BSSID = "ff:ff:ff:ff:ff:ff" if frame.haslayer(Dot11): if frame.type == 2: #toDS from DS holdes i FCField (Frame Control Field) #Vi henter hele fc fieldet ved frame.FCfield & 0x03 (["to-DS", "from-DS", "MF", "retry", "pw-mgt", "MD", "wep", "order"]) #Og retriever derefter toDS og fromDS ved nedestående. DS = frame.FCfield & 0x03 toDS = DS & 0x01 != 0 fromDS = DS & 0x2 != 0 #source: https://mrncciew.files.wordpress.com/2014/09/cwap-mac-address-01.png if toDS == 0 and fromDS == 0: # dette burde KUN være data frames der sendes til AP. RA = DA = frame.addr1.upper( ) # RA= REciver, DA = fianl destination TA = SA = frame.addr2.upper() BSSID = frame.addr3.upper() elif toDS == 0 and fromDS == 1: RA = DA = frame.addr1.upper( ) # RA= REciver, DA = fianl destination TA = BSSID = frame.addr2.upper() SA = frame.addr3.upper() elif toDS == 1 and fromDS == 0: RA = BSSID = frame.addr1.upper() TA = SA = frame.addr2.upper() DA = frame.addr3.upper() elif toDS == 1 and fromDS == 1: RA = frame.addr1.upper() TA = frame.addr2.upper() DA = frame.addr3.upper() SA = frame.addr4.upper() else: SA = "ff:ff:ff:ff:ff:ff" # dette burde ikke kunne ske BSSID = "ff:ff:ff:ff:ff:ff" if SA not in STA_list and BSSID == bssidsearch: STA_list.append(SA) self.sniffStationbox.addItem("Found Station: " + SA + " From AccessPoint: " + BSSID) print("Found Station: " + SA + " From AccessPoint: " + BSSID) def update_attacklabel(self): self.framelabel.setText("Seconds : " + str(sentTimeSpend) + "\n\n" + "Sent : " + str(framecount) + "\n" + "DeAuthentication Frames") def snifferfunction(self): sniff(iface="wlan0mon", count=0, prn=self.FindSSIDtest, store=0, stop_filter=self.checkifstop) def stationSniffer(self): sniff(iface="wlan0mon", count=0, prn=lambda fr: self.FindSTAinSpecificBSSID( self.textboxAP.text(), fr, self.channeltextbox.text()), store=0, stop_filter=self.checkifstop) @pyqtSlot() def on_stationsniff(self): global breaksniff_flag self.sniffbox.clear() self.sniffStationbox.clear() self.sniffbox.hide() self.sniffStationbox.show() breaksniff_flag = False print("STARTED STATION SNIFF") stationthread = threading.Thread(target=self.stationSniffer) stationthread.start() @pyqtSlot() def on_ssidsniff(self): global breaksniff_flag global showStationButton self.sniffbox.clear() self.sniffStationbox.clear() self.sniffbox.show() self.sniffStationbox.hide() self.sniffStationbutton.show() breaksniff_flag = False print("STARTED SSID/BSSID SNIFF") channelThread = threading.Thread(target=setChannel) channelThread.start() sniffingthread = threading.Thread(target=self.snifferfunction) sniffingthread.start() @pyqtSlot() def on_attackclick(self): global resetflag global framecount print("AMOUNT OF ACTIVE THREADS" + str(threading.active_count())) resetflag = False self.textboxAP.setEnabled(False) self.textbox.setEnabled(False) self.textbox_amount.setEnabled(False) self.channeltextbox.setEnabled(False) bssid_targetMAC = self.textboxAP.text() #string destMAC = self.textbox.text() #string frame_amount_entered = int(self.textbox_amount.text()) channel_attack_value = int(self.channeltextbox.text()) print(bssid_targetMAC) print(destMAC) matchexpr = "[0-9a-f]{2}([-:]?)[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$" #regex match timer = QtCore.QTimer(self) timer.timeout.connect(self.update_attacklabel) if re.match(matchexpr, bssid_targetMAC.lower()) and re.match( matchexpr, destMAC.lower()) and ( 13 >= channel_attack_value >= 1 ): #checks if both inputs are valid MAC addreses (just format) print("VALID VALUES") attackthread = threading.Thread( target=perform_deauth_attack, args=(iface, destMAC, bssid_targetMAC, frame_amount_entered, channel_attack_value)) attackthread.start() print("AMOUNT OF ACTIVE THREADS" + str(threading.active_count())) timer.start( 2 ) #updatere lige nu hvert 2'ende milisekund, det måske LIDT for hurtigt, men det fungerer fint. else: self.textbox_amount.setPlaceholderText("Enter amount of frames") self.textboxAP.setPlaceholderText("Enter valid AP MAC address") self.textbox.setPlaceholderText( "Enter valid destination MAC address") self.textboxAP.setEnabled(True) self.textbox.setEnabled(True) self.textbox_amount.setEnabled(True) self.channeltextbox.setEnabled(True) self.textbox.clear() self.textboxAP.clear() self.textbox_amount.clear() self.channeltextbox.clear() @pyqtSlot() def on_stopclick(self): global breaksniff_flag breaksniff_flag = True @pyqtSlot() def on_resetclick(self): global resetflag global framecount global breaksniff_flag global channel_value global sentTimeSpend self.textbox.clear() self.textboxAP.clear() self.textbox_amount.clear() self.channeltextbox.clear() self.sniffbox.clear() self.sniffStationbox.clear() self.textboxAP.setEnabled(True) self.textbox.setEnabled(True) self.textbox_amount.setEnabled(True) self.channeltextbox.setEnabled(True) self.textboxAP.setPlaceholderText("Enter the target AP MAC address") self.textbox.setPlaceholderText("Enter the target MAC address") self.textbox_amount.setPlaceholderText("Enter amount of seconds") self.channeltextbox.setPlaceholderText( "Enter the channel for the attack") self.sniffStationbutton.hide() resetflag = True breaksniff_flag = True framecount = 0 sentTimeSpend = 0 channel_value = 1 del ssid_bssid[:] del STA_list[:] self.framelabel.setText("Seconds : " + str(sentTimeSpend) + "\n\n" + "Sent : " + str(framecount) + "\n" + "DeAuthentication Frames") self.framelabel.repaint()