Exemplo n.º 1
0
    def setupGui(self):
        width = 185  # window width
        height = 100 # window height
        title = "Wave Sender" # window title
        self.resize(width, height)
        self.move(app.desktop().availableGeometry().width() / 2 - 250 / 2, app.desktop().availableGeometry().height() / 2 - 150 / 2) # move window to visible desktop center
        self.setWindowTitle(title)

        # input for assigning an IP-address which server listens
        input_ip = QLineEdit(str(self.server.ip), self)
        input_ip.resize(120, input_ip.height())
        input_ip.move(5, 25)

        # input for assigning a port which server listens
        input_port = QLineEdit(str(self.server.port), self)
        input_port.resize(50, input_port.height())
        input_port.move(130, 25)

        # input for assigning a port which server listens
        label_ip = QLabel("IP-address:", self)
        label_ip.move(10, 5)

        # input for assigning a port which server listens
        label_port = QLabel("Port:", self)
        label_port.move(135, 5)

        self.label_status = QLabel("No connection to client", self)
        self.label_status.move(10, 80)
Exemplo n.º 2
0
    def setMasteryTree(self, tree, imageList):
        yPos = 3
        xPos = 7
        column = 1
        for element in imageList.keys():
            if not isinstance(element, str):
                mastery = QLabel(tree)
                mastery.setScaledContents(True)
                mastery.move(xPos, yPos)
                mastery.resize(30, 30)
                mastery.setPixmap(imageList[element])

                mastery_rank = QLabel(tree)
                mastery_rank.move(xPos + 31, yPos + 15)
                mastery_rank.resize(15, 15)
                mastery_rank.setAlignment(Qt.AlignCenter)
                mastery_rank.setText('0')
                mastery_rank.setStyleSheet(
                    "QLabel {color:white; border-style: outset; border-width: 2px; border-color: black}"
                )
                self.mastery_rank_labels[element] = mastery_rank
            if column < 3:
                xPos += 56
                column += 1
            else:
                column = 1
                xPos = 7
                yPos += 35
Exemplo n.º 3
0
class App(QWidget):
    def __init__(self):
            super(App,self).__init__()
            self.title = 'PyQt4 Video'
            self.left = 100
            self.top = 100
            self.width = 640
            self.height = 480
            self.initUI()

    def initUI(self):
            self.setWindowTitle(self.title)
            self.setGeometry(self.left, self.top, self.width, self.height)
            self.resize(800, 600)
            # create a label
            self.label = QLabel(self)
            self.label.move(0, 0)
            self.label.resize(640, 480)
            th = Thread(self)
            th.changePixmap.connect(lambda p: self.setPixMap(p))
            th.start()

    def setPixMap(self, p):     
        p = QPixmap.fromImage(p)    
        p = p.scaled(640, 480, Qt.KeepAspectRatio)
        self.label.setPixmap(p)
Exemplo n.º 4
0
 def add_line(self, cord_1, cord_2, color):
     key = tuple(sorted([tuple(cord_1), tuple(cord_2)]))
     x = min(cord_1[0], cord_2[0])
     y = min(cord_1[1], cord_2[1])
     if key in self.lines:
         print("ERROR: Line between {} and {} already added.".format(
             cord_1, cord_2))
     else:
         line = QLabel(self)
         if color == "white":
             pixmap = QPixmap(get_asset_path("hor_line_white"))
         else:
             pixmap = QPixmap(get_asset_path("hor_line_black"))
         c1 = (30 + cord_1[0] * 30, 30 + cord_1[1] * 30)
         c2 = (30 + cord_2[0] * 30, 30 + cord_2[1] * 30)
         length = ((c1[0] - c2[0])**2 + (c1[1] - c2[1])**2)**(1 / 2)
         angle = math.degrees(
             math.atan2(key[1][1] - key[0][1], key[1][0] - key[0][0]))
         pixmap = pixmap.scaled(length, 5)
         pixmap = pixmap.transformed(QTransform().rotate(angle))
         line.setPixmap(pixmap)
         line.move(30 + x * 30, 30 + y * 30)
         line.show()
         line.lower()
         self.lines[key] = line
Exemplo n.º 5
0
class LocalityWidGet(QWidget):
    """Modal para alterer a localidade da previção do tempo"""
    
    def __init__(self):
        super(LocalityWidGet, self).__init__()
        
        self.setWindowTitle = 'Settings'
        self.setGeometry(450, 300, 400, 200)

        self.locality_label = QLabel('Localidade: ',self)
        self.locality_label.move(20, 35)

        self.locality_label_example = QLabel('Exemplo: Porto Alegre, RS', self)
        self.locality_label_example.move(100, 60)

        self.locality_input_text = QLineEdit(self)
        self.locality_input_text.move(100, 30)

        wc = WeatherClient()
        current_locality = wc.get_place()
        self.locality_input_text.setText(current_locality.replace('+', ', ').decode('utf-8'))

        self.btnOk = QPushButton('OK', self)
        self.btnOk.move(250, 150)
        self.btnOk.clicked.connect(lambda: Eventer.save_new_locality(self))


        self.show()
Exemplo n.º 6
0
class orale(QDialog):

    def __init__(self):

        super(orale, self).__init__(None)
        
        self.resize(245, 300)
        self.setWindowTitle('Saliendo de Telefonia')

        self.p = QLabel('Desea Cerrar el Programa?',self)
        self.p.move(10,10)
        
        self.imaje = QLabel(self)
        self.imaje.setGeometry(10,60,225,225)
        self.imaje.setPixmap(QPixmap("duda.png"))
        
        self.salirsi = QPushButton('Si', self)
        self.salirsi.setGeometry(60, 30, 60, 30)
        
        self.salirno = QPushButton('No', self)
        self.salirno.setGeometry(125, 30, 60, 30)

        self.connect(self.salirsi, SIGNAL('clicked()'), lambda: self.salir())
        self.connect(self.salirno, SIGNAL('clicked()'), lambda: self.close())

    def salir(self):
		exit()
Exemplo n.º 7
0
    def create_label(self, name, pos_x, pos_y):
        """
        Se define un metodo para la creacion de los labels de la interfaz grafica
        :param name: Nombre del label
        :param pos_x: Posicion horizontal
        :param pos_y: Posicion vertical

        """
        label = QLabel(name, self)
        label.move(pos_x, pos_y)
        label.resize(label.minimumSizeHint())
Exemplo n.º 8
0
class VentanaMenu(QMainWindow):
    def __init__(self):
        super(VentanaMenu, self).__init__()
        self.inicializar()
        
    def inicializar(self):
        self.titulo = QLabel("PROCESAMIENTO DIGITAL DE IMAGENES", self)
        self.titulo.move(50,50)
        self.titulo.adjustSize()
        
        self.filtrar = QPushButton("Filtrar", self)
        self.filtrar.move(100,100)
        self.filtrar.clicked.connect(self.abrirFiltrar)
        
        self.analizar = QPushButton("Analizar", self)
        self.analizar.move(100,150)
        self.analizar.clicked.connect(self.abrirAnalizar)
        
        self.invertir = QPushButton("Invertir", self)
        self.invertir.move(100,200)
        self.invertir.clicked.connect(self.abrirInvertir)
        self.setWindowTitle("Transformada de Fourier")
        self.resize(300,300)
        self.setSizePolicy(QSizePolicy.Fixed,QSizePolicy.Fixed)
        self.show()
        
    def abrirFiltrar(self):
        self.ventanaFiltrar = VentanaFiltrar(self)
    
    def abrirAnalizar(self):
        archivo = QFileDialog(self)
        ruta = archivo.getOpenFileName(self, 'Seleccionar imagen', '', "Images (*.png *.gif *.jpg *.bmp)")
        if not ruta.isEmpty():
            try:
                from core import transformar
                img1, img2 = transformar(str(ruta))
                ruta1 = archivo.getSaveFileName(self, "Guardar Magnitud", '', "Images (*.png *.gif *.jpg *.bmp)")
                img1.save(str(ruta1) + ".png")
                ruta2 = archivo.getSaveFileName(self, "Guardar Fase", '', "Images (*.png *.gif *.jpg *.bmp)")
                img2.save(str(ruta2) + ".png")
            except ImportError:
                resp = QMessageBox.information(self, 'Error', 'Hubo un error inesperado', 
                                        QMessageBox.Ok, QMessageBox.NoButton)
        else:
            resp = QMessageBox.information(self, 'Error', 'No ha elegido imagenes', 
                                        QMessageBox.Ok, QMessageBox.NoButton)
    
    def abrirInvertir(self):
        self.ventanaInversa = VentanaInvertir(self)
Exemplo n.º 9
0
class about(QDialog):

    def __init__(self):

        super(about, self).__init__(None)
        
        self.resize(560, 240)
        self.setWindowTitle('Acerca de')
        
        self.imaje = QLabel(self)
        self.imaje.setGeometry(300,10,249,203)
        self.imaje.setPixmap(QPixmap("proyecto.png"))
        
        self.n = QLabel('Proyectos 980 \nGrupo 2 \n\nIntegrantes: \n\nJason Hernandez \t201020518 \nChristian Flores \t\t201212650 \nHasler Herrera \t\t201046499 \nDennis Conde \t\t201245425 \nCarlos Salcedo \t\t201020527 \nSamuel Choc \t\t201318619',self)
        self.n.move(10,10)
Exemplo n.º 10
0
class WaveSenderWindow(QDialog):
    def __init__(self, parent=None):
        super(WaveSenderWindow, self).__init__(parent)
        self.setupServer()
        self.setupGui()

    def setupServer(self):
        self.server = SomeServer()
        self.server.ip = args.ip
        self.server.port = args.port
        self.server.startListen()

    def setupGui(self):
        width = 185  # window width
        height = 100 # window height
        title = "Wave Sender" # window title
        self.resize(width, height)
        self.move(app.desktop().availableGeometry().width() / 2 - 250 / 2, app.desktop().availableGeometry().height() / 2 - 150 / 2) # move window to visible desktop center
        self.setWindowTitle(title)

        # input for assigning an IP-address which server listens
        input_ip = QLineEdit(str(self.server.ip), self)
        input_ip.resize(120, input_ip.height())
        input_ip.move(5, 25)

        # input for assigning a port which server listens
        input_port = QLineEdit(str(self.server.port), self)
        input_port.resize(50, input_port.height())
        input_port.move(130, 25)

        # input for assigning a port which server listens
        label_ip = QLabel("IP-address:", self)
        label_ip.move(10, 5)

        # input for assigning a port which server listens
        label_port = QLabel("Port:", self)
        label_port.move(135, 5)

        self.label_status = QLabel("No connection to client", self)
        self.label_status.move(10, 80)

    # perform a proper exit procedure
    def closeEvent(self, evnt):
        super(WaveSenderWindow, self).closeEvent(evnt)
        if self.server.recorder_thread:
            if self.server.recorder_thread.isAlive() == True: # check if recorder thread is running
                self.server.recorder.terminationFlag = True # tell the recorder to stop
                self.server.recorder_thread.join() # wait for recorder to stop
Exemplo n.º 11
0
 def show_dialog(dialog_str, showed_msg):
     d = QDialog()
     d.setGeometry(500, 400, 200, 60)
     icon = QtGui.QIcon()
     icon.addPixmap(
         QtGui.QPixmap(design._fromUtf8("gui_assets/app_logo.png")),
         QtGui.QIcon.Normal, QtGui.QIcon.Off)
     d.setWindowIcon(icon)
     label = QLabel(showed_msg, d)
     label.move(10, 10)
     button = QPushButton('Ok', d)
     button.move(100, 100)
     button.connect(button, SIGNAL("clicked()"), d.close)
     d.setWindowTitle(dialog_str)
     d.setWindowModality(Qt.ApplicationModal)
     d.exec_()
Exemplo n.º 12
0
    def initUI(self):
        label = QLabel(self)
        img = cv2.resize(self.img, (600, 300))
        height, width, channel = img.shape
        bytesPerLine = 3 * width
        image = QtGui.QImage(img.data, width, height, bytesPerLine,
                             QtGui.QImage.Format_RGB888)
        pixmap = QtGui.QPixmap(image)
        # pixmap = QtGui.QPixmap(self.img).scaled(
        #     300, 300, QtCore.Qt.KeepAspectRatioByExpanding, QtCore.Qt.SmoothTransformation)
        label.setPixmap(pixmap)
        label.move(25, 25)

        label_h_rules = QLabel("Rules:", self)
        label_h_rules.setFont(QtGui.QFont("Times", 14, QtGui.QFont.Bold))
        label_h_rules.move(50, 350)
        label_rules = QLabel(self.rules, self)
        label_rules.setFont(QtGui.QFont("Times", 14))
        label_rules.move(60, 380)

        label_h_info = QLabel("Info:", self)
        label_h_info.setFont(QtGui.QFont("Times", 14, QtGui.QFont.Bold))
        label_h_info.move(400, 350)
        label_info = QLabel(self.info, self)
        label_info.setFont(QtGui.QFont("Times", 14))
        label_info.move(410, 380)

        resolve_button = QPushButton("Resolve", self)
        resolve_button.clicked.connect(self.on_resolve)
        resolve_button.move(50, 550)
        resolve_button.setEnabled(self.alert.is_resolved)

        ignore_button = QPushButton("Ignore", self)
        ignore_button.clicked.connect(self.on_ignore)
        ignore_button.move(250, 550)

        if self.alert.state != 'alert':
            resolve_button.setEnabled(False)
            ignore_button.setEnabled(False)

        cancel_button = QPushButton("Cancel", self)
        cancel_button.clicked.connect(self.on_cancel)
        cancel_button.move(450, 550)

        self.setGeometry(self.left, self.top, self.width, self.height)
        self.show()
Exemplo n.º 13
0
class finalMenu(object):
    def FinalMenu(self, MainWindow):
        self.kid = MainWindow.kid
        self.order = self.kid.order()
        self.f = ''
        for i in self.order:
            self.f = self.f + i + '\n'
        MainWindow.setGeometry(50, 50, 400, 450)
        # MainWindow.setFixedSize(400, 450)
        MainWindow.setWindowTitle("Final Menu")
        self.w = QWidget(MainWindow)
        self.l = QLabel("Final Menu", self.w)
        self.finalLabel = QLabel(self.f, self.w)
        # self.finalLabel.move(50,50)
        self.l.move(170, 0)
        self.finalLabel.move(170, 100)
        MainWindow.setCentralWidget(self.w)
Exemplo n.º 14
0
 def show_intro_dialog(dialog_str='dialog'):
     d = QDialog()
     d.setGeometry(500, 400, 340, 150)
     icon = QtGui.QIcon()
     icon.addPixmap(
         QtGui.QPixmap(design._fromUtf8("gui_assets/app_logo.png")),
         QtGui.QIcon.Normal, QtGui.QIcon.Off)
     d.setWindowIcon(icon)
     label = QLabel(
         '    Welcome to Comment Analyzer v1.0!\n    This program is made by Berk Sudan.',
         d)
     label.move(50, 50)
     button = QPushButton('Forward to program', d)
     button.move(100, 100)
     button.connect(button, SIGNAL("clicked()"), d.close)
     d.setWindowTitle(dialog_str)
     d.setWindowModality(Qt.ApplicationModal)
     d.exec_()
Exemplo n.º 15
0
class VentanaFiltrar(QDialog):
    def __init__(self, padre):
        super(VentanaFiltrar, self).__init__(padre)
        self.inicializar()
    
    def inicializar(self):
        self.titulo = QLabel("SELECCIONE EL FILTRO A APLICAR", self)
        self.titulo.move(50,50)
        self.titulo.adjustSize()
        
        self.filtros = QComboBox(self)
        self.filtros.move(100,100)
        self.filtros.sizeAdjustPolicy()
        self.filtros.addItem("Low pass filter")
        self.filtros.addItem("High pass filter")
        self.filtros.addItem("Gaussian filter")
        self.filtros.addItem("Pyramidal filter")
        self.filtros.addItem("Sinc filter")
        
        self.seleccionar = QPushButton("Seleccionar imagen", self)
        self.seleccionar.move(100,200)
        self.seleccionar.clicked.connect(self.filtrar)
        self.setWindowTitle("Filtrar una imagen")
        self.resize(300,300)
        self.setWindowModality(1)
        self.setSizePolicy(QSizePolicy.Fixed,QSizePolicy.Fixed)
        self.show()
        
    def filtrar(self):
        archivo = QFileDialog(self)
        ruta = archivo.getOpenFileName(self, 'Seleccionar imagen', '', "Images (*.png *.gif *.jpg *.bmp)")
        if not ruta.isEmpty():
            try:
                from core import filtrar
                img = filtrar(str(ruta), str(self.filtros.currentText()))
                ruta1 = archivo.getSaveFileName(self, "Guardar imagen", '', "Images (*.png *.gif *.jpg *.bmp)")
                img.save(str(ruta1) + ".png")
            except ImportError:
                resp = QMessageBox.information(self, 'Error', 'Hubo un error inesperado', 
                                        QMessageBox.Ok, QMessageBox.NoButton)
        else:
            resp = QMessageBox.information(self, 'Error', 'No ha elegido imagenes', 
                                        QMessageBox.Ok, QMessageBox.NoButton)
Exemplo n.º 16
0
class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)

        self.setFixedSize(600, 600)
        self.label = QLabel(self)
        self.label.setFixedWidth(400)
        self.label.setFixedHeight(400)
        self.label.setAlignment(Qt.AlignCenter)
        self.label.setText(u"这个标签的长裤可以变化吗aaaaaaaa东西南北?")

        pe = QPalette()
        pe.setColor(QPalette.WindowText, Qt.red)
        # self.label.setAutoFillBackground(True)
        # pe.setColor(QPalette.Window, Qt.blue)
        # pe.setColor(QPalette.Background,Qt.blue)
        self.label.setPalette(pe)

        self.label.setFont(QFont("Roman times", 10, QFont.Bold))

        self.label.move(100, 100)
Exemplo n.º 17
0
    class Example(QWidget):
        def __init__(self):
            super(Example, self).__init__()

            self.initUI()

        def initUI(self):

            vbox = QVBoxLayout()

            btn = QPushButton('Dialog', self)
            btn.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

            btn.move(20, 20)

            vbox.addWidget(btn)

            btn.clicked.connect(self.showDialog)

            self.lbl = QLabel('Cosmic Well-Being', self)
            self.lbl.move(130, 20)

            vbox.addWidget(self.lbl)
            self.setLayout(vbox)

            self.setGeometry(300, 300, 250, 180)
            self.setWindowTitle('Font dialog')
            self.show()

        def showDialog(self):

            resultD, ok = getOutput(inputD={
                'three': 3,
                'eps': 25,
                'Fvac': 125.5
            })
            if ok:
                print 'resultD =', resultD
                print 'ok   =', ok
                self.lbl.setText('%s' % (resultD, ))
Exemplo n.º 18
0
class VentanaInvertir(QDialog):
    def __init__(self, padre):
        super(VentanaInvertir, self).__init__(padre)
        self.inicializar()
        
    def inicializar(self):
        self.titulo = QLabel("SELECCIONE LAS IMAGENES DE MAGNITUD Y FASE", self)
        self.titulo.move(50,50)
        self.titulo.adjustSize()
        
        self.magnitud = QPushButton("magnitud", self)
        self.magnitud.move(100,200)
        self.magnitud.clicked.connect(self.seleccionar)
        """
        self.fase = QPushButton("fase", self)
        self.fase.move(100,150)
        self.fase.clicked.connect(self.seleccionar)
        """
        self.setWindowTitle("Transformada Inversa")
        self.resize(300,300)
        self.setWindowModality(1)
        self.setSizePolicy(QSizePolicy.Fixed,QSizePolicy.Fixed)
        self.show()
        
    def seleccionar(self):
        archivo = QFileDialog(self)
        ruta1 = archivo.getOpenFileName(self, 'Seleccionar magnitud', '', "Images (*.png *.gif *.jpg *.bmp)")
        ruta2 = archivo.getOpenFileName(self, 'Seleccionar fase', '', "Images (*.png *.gif *.jpg *.bmp)")
        if not ruta1.isEmpty() and not ruta2.isEmpty():
            from core import invertir, NoCorrespondenError
            try:
                img = invertir((str(ruta1), str(ruta2)))
                ruta3 = archivo.getSaveFileName(self, 'Guardar imagen', '', "Images (*.png *.gif *.jpg *.bmp)")
                img.save(str(ruta3) + ".png")
            except NoCorrespondenError:
                resp = QMessageBox.information(self, 'Error', 'Las imagenes no corresponden', 
                                        QMessageBox.Ok, QMessageBox.NoButton)    
        else:
            resp = QMessageBox.information(self, 'Error', 'No ha elegido imagenes', 
                                        QMessageBox.Ok, QMessageBox.NoButton)
Exemplo n.º 19
0
class Bomb(Piece):
    def __init__(self, piece_type, number=5, parent=None):
        super().__init__(piece_type, parent)
        self._number = number
        self._number_label = QLabel(self)
        self._number_label.setText(str(self._number))
        self._number_label.move(40, 38)
        font = QFont()
        font.setBold(True)
        font.setPixelSize(30)
        self._number_label.setFont(font)
        self._number_label.setStyleSheet("color: white;")
        self._number_label.show()

    @property
    def number(self):
        return self._number

    @number.setter
    def number(self, value):
        self._number = value
        self._number_label.setText(str(self._number))
Exemplo n.º 20
0
    class Example(QWidget):
        
        def __init__(self):
            super(Example, self).__init__()
            
            self.initUI()
            
        def initUI(self):      

            vbox = QVBoxLayout()

            btn = QPushButton('Dialog', self)
            btn.setSizePolicy(QSizePolicy.Fixed,
                QSizePolicy.Fixed)
            
            btn.move(20, 20)

            vbox.addWidget(btn)

            btn.clicked.connect(self.showDialog)
            
            self.lbl = QLabel('Cosmic Well-Being', self)
            self.lbl.move(130, 20)

            vbox.addWidget(self.lbl)
            self.setLayout(vbox)          
            
            self.setGeometry(300, 300, 250, 180)
            self.setWindowTitle('Font dialog')
            self.show()
            
        def showDialog(self):
            
            resultD, ok = getOutput( inputD = {'three':3, 'eps':25, 'Fvac':125.5})
            if ok:
                print 'resultD =',resultD
                print 'ok   =',ok
                self.lbl.setText('%s'%(resultD,))
Exemplo n.º 21
0
class Bomb(Piece):

    def __init__(self, piece_type, number=5, parent=None):
        super().__init__(piece_type, parent)
        self._number = number
        self._number_label = QLabel(self)
        self._number_label.setText(str(self._number))
        self._number_label.move(40, 38)
        font = QFont()
        font.setBold(True)
        font.setPixelSize(30)
        self._number_label.setFont(font)
        self._number_label.setStyleSheet("color: white;")
        self._number_label.show()

    @property
    def number(self):
        return self._number

    @number.setter
    def number(self, value):
        self._number = value
        self._number_label.setText(str(self._number))
Exemplo n.º 22
0
    def __init__(self):

        #self.setWindowIcon(QIcon("icon.png"))
        QMainWindow.__init__(self)

        myappid = u'ds.daishin.cbpProject Linker.10'  # arbitrary string
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)

        #윈도우 특성 설정
        self.setWindowTitle('CBP Project Linker')  # 윈도우 타이틀 지정 선언문
        self.setWindowIcon(QIcon("cbplinkericon.png"))
        self.setGeometry(600, 600, 450, 200)  # 윈도우 위치/크기 설정 문법
        #self.statusBar().showMessage('ready')

        idtext = QLabel(self)
        idtext.text()
        #idtext.resize(15,15)
        idtext.setText("Project Path : ")
        idtext.move(35, 20)

        pwtext = QLabel(self)
        pwtext.text()
        #idtext.resize(15,10)
        pwtext.setText("Link Impl Path : ")
        pwtext.move(35, 50)

        mdtext = QLabel(self)
        mdtext.text()
        mdtext.resize(300, 20)
        mdtext.setText("CBP Project Linker. Made ByJJuN. v1.0")
        mdtext.move(110, 180)

        #Project Text Box
        self.projectbox = QLineEdit(self)
        self.projectbox.setText("C:\GIT_AREA\cybos_psl")
        self.projectbox.resize(300, 25)
        self.projectbox.move(135, 20)

        #Link Project 용 Text Box
        self.linkimplbox = QLineEdit(self)
        self.linkimplbox.setText("C:\GIT_AREA\cybos_cii\CIIImpl")
        self.linkimplbox.resize(300, 25)
        self.linkimplbox.move(135, 50)

        # 버튼1 추가
        btn1 = QPushButton('MAKE Link', self)
        #btn1.resize(btn1.sizeHint())
        btn1.move(160, 90)
        btn1.clicked.connect(self.btnClicked)

        # 종료 버튼 추가
        btnQuit = QPushButton('EXIT', self)
        btnQuit.move(160, 130)  # 종료창 위치/크기 설정
        btnQuit.clicked.connect(QCoreApplication.instance().quit)

        #윈도우 화면 출력
        self.show()
    def listCategory_clicked(self, category):
        self.categoryWindow = QWidget()
        c = self.categoryWindow
        c.setWindowTitle("Search dataset by category")
        c.setMinimumSize(600, 500)
        
        # Category list showing all posible options
        label1 = QLabel("Options by {0}:".format(category), c)
        label1.move(50, 20)
        label1.show()
        categoryListWidget = QListWidget(c)
        optionSet = set()
        for key in self.climateData:
            optionSet.add(self.climateData[key][category])
        for option in sorted(list(optionSet)):
            item = QListWidgetItem(option)
            item.setData(Qt.UserRole, option)
            categoryListWidget.addItem(item)
        categoryListWidget.move(50, 50)
        categoryListWidget.resize(200, 400)
        categoryListWidget.show()
        categoryListWidget.clicked.connect(lambda: self.categoryItem_clicked(\
            category, categoryListWidget.currentItem().data(Qt.UserRole)))

        # List showing all datasets associated with the selected option
        label2 = QLabel("Available Datasets:", c)
        label2.move(250, 20)
        label2.show()
        self.datasetListWidget = QListWidget(c)
        self.datasetListWidget.move(250, 50)
        self.datasetListWidget.resize(400, 400)
        self.datasetListWidget.show()

        c.move(QtGui.QApplication.desktop().screen().rect().center() - \
            c.rect().center())
        c.show()
Exemplo n.º 24
0
class MainWindow(QWidget):

    def __init__(self, parent=None):
        super().__init__(parent)
        self.__timer = QTimer(self)
        self.background = QLabel(self)
        self.background.setPixmap(QPixmap(get_asset_path(["background.png"])))
        self.__entities = []
        self.__team_1_label = QLabel("Gold Team 1: 0", self)
        self.__team_1_label.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
        # self.__team_1_label.setFixedWidth(600)
        self.__font = QFont("", 20)
        self.__font.setBold(True)
        self.__team_1_label.setStyleSheet("color: yellow;")
        self.__team_1_label.setFont(self.__font)
        self.__team_2_label = QLabel("Gold Team 2: 0", self)
        self.__team_2_label.setStyleSheet("color: yellow;")
        self.__team_2_label.setFont(self.__font)
        # self.__team_2_label.setFixedWidth(600)
        self.__team_2_label.move(self.width() - self.__team_2_label.sizeHint().width(), 0)
        self.__objective_label = QLabel("Objective: None", self)
        self.__font_objective = QFont("", 15)
        self.__font_objective.setBold(True)
        self.__objective_label.setFont(self.__font_objective)
        self.__objective_label.move(self.width()//2 - self.__objective_label.sizeHint().width()//2, 0)

    def startMain(self, main, delay=25):
        self.__timer.timeout.connect(main)
        self.__timer.start(delay)

    def add_entity(self, entity):
        entity.setParent(self)
        entity.show()
        self.__entities.append(entity)

    def set_gold_t1(self, gold):
        self.__team_1_label.setText("Gold Team 1: {}".format(gold))
        self.__team_1_label.setFixedWidth(self.__team_1_label.sizeHint().width())

    def set_gold_t2(self, gold):
        self.__team_2_label.setText("Gold Team 2: {}".format(gold))
        self.__team_2_label.setFixedWidth(self.__team_2_label.sizeHint().width())
        self.__team_2_label.move(self.width() - self.__team_2_label.sizeHint().width(), 0)

    def set_objective(self, objective):
        self.__objective_label.setText("Objective: {}".format(objective))
        self.__objective_label.move(self.width() // 2 - self.__objective_label.sizeHint().width() // 2, 0)

    def keyPressEvent(self, e):
        if e.key() == Qt.Key_Space:
            print(len(self.__entities))
            print("Testing")

    def setFixedSize(self, *__args):
        super().setFixedSize(*__args)
        self.__team_2_label.move(self.width() - self.__team_2_label.sizeHint().width(), 0)
        self.__objective_label.move(self.width() // 2 - self.__objective_label.sizeHint().width() // 2, 0)
Exemplo n.º 25
0
class EGPSWindow(QMainWindow):
    def __init__(self):
        # Inicializo el parent y audio module
        super(EGPSWindow, self).__init__()
        self.audio_mod = AudioModule(OUTPUT_FILE_PATH)

        # Titulo, tamano y tamano fijo (no resize)
        win_height = 130 + len(TRANSFER_FUNCTIONS) * 40
        self.setWindowTitle("EGPS-1")
        self.setGeometry(70, 70, 600, win_height)
        self.setFixedSize(600, win_height)

        # Funcion y lista de parametros para la creacion de las labels
        labels_func = self.create_label
        nm_px_py_labels = [("Transductor de entrada", 10, 105),
                           ("Grabacion", 400, 120), ("Salida", 400, 330),
                           ("Archivo de entrada", 10, 10),
                           ("Transductor de salida", 200, 105),
                           ("Entrada a procesar", 400, 230)]

        # Funcion y lista de parametros para la creacion de radiobuttons
        in_bq = QButtonGroup(self)
        out_bq = QButtonGroup(self)
        process_bq = QButtonGroup(self)
        radio_buttons_func = self.create_radio_button
        nm_px_py_cb_radio_buttons = [
            ("Archivo de entrada", 405, 255, PROCESS_GROUP, process_bq),
            ("Grabacion", 405, 280, PROCESS_GROUP, process_bq)
        ]

        #Creacion de los radio buttons para el grupo de transductores de entrada y de salida
        for index, transfer_function in enumerate(TRANSFER_FUNCTIONS.keys()):
            nm_px_py_cb_radio_buttons.append(
                (transfer_function, 30, 125 + index * 40, INPUT_GROUP, in_bq))
            nm_px_py_cb_radio_buttons.append(
                (transfer_function, 220, 125 + index * 40, OUTPUT_GROUP,
                 out_bq))

        # Funcion y lista de parametros para la creacion de los pushbuttons
        push_buttons_func = self.define_push_button
        nm_px_py_callb_push_buttons = [
            ("", 55, 70, self.audio_mod.stop_file, STOP_IMAGE_PATH, True),
            ("Elegir archivo", 15, 35, self.select_file),
            ("", 15, 70, self.audio_mod.play_file, PLAY_IMAGE_PATH, True),
            ("", 405, 145, self.audio_mod.rec, REC_IMAGE_PATH, True),
            ("", 445, 145, self.audio_mod.stop_rec, STOP_IMAGE_PATH, True),
            ("", 485, 145, self.audio_mod.play_rec, PLAY_IMAGE_PATH, True),
            ("", 525, 145, self.rec_file_save, SAVE_IMAGE_PATH, True),
            ("", 405, 355, self.out_file_play, PLAY_IMAGE_PATH, True),
            ("", 445, 355, self.audio_mod.stop_out, STOP_IMAGE_PATH, True),
            ("", 485, 355, self.out_file_save, SAVE_IMAGE_PATH, True)
        ]

        # Se define una lista de tuplas con (constructor, lista de parametros del constructor) para los diferentes
        # tipos de elementos
        elements_constructors = [
            (labels_func, nm_px_py_labels),
            (radio_buttons_func, nm_px_py_cb_radio_buttons),
            (push_buttons_func, nm_px_py_callb_push_buttons)
        ]

        for const, params_list in elements_constructors:
            for params in params_list:
                const(*params)

        # Se eligen los radiobuttons iniciales
        self.input_output = dict()
        self.input_output[INPUT_GROUP] = str(in_bq.buttons()[0].text())
        self.input_output[OUTPUT_GROUP] = str(out_bq.buttons()[1].text())
        self.input_output[PROCESS_GROUP] = str(process_bq.buttons()[0].text())
        in_bq.buttons()[0].setChecked(True)
        out_bq.buttons()[1].setChecked(True)
        process_bq.buttons()[0].setChecked(True)

        # Se define el pop up para salir de la aplicacion
        self.msg_box = QMessageBox()
        self.msg_box.setWindowTitle("Salir")
        self.msg_box.setText("Esta seguro que desea salir?")
        self.msg_box.addButton("Si", QMessageBox.AcceptRole)
        self.msg_box.addButton("No", QMessageBox.RejectRole)

        # Error para formato incorrecto
        self.wrong_file_box = QMessageBox()
        self.wrong_file_box.setWindowTitle("Error")
        self.wrong_file_box.setText("El archivo tiene formato incorrecto")

        # Error para el path file
        self.no_data_box = QMessageBox()
        self.no_data_box.setWindowTitle("Error")
        self.no_data_box.setText(
            "No se puede utilizar la ruta indicada o los datos son inexistentes"
        )

        # Create select play file
        self.path_label = QLabel(os.path.abspath(OUTPUT_FILE_PATH), self)
        self.path_label.move(128, 40)
        self.path_label.resize(self.path_label.minimumSizeHint())

        # Metodo del parent QWidget. QWidget -> QMainWindow -> EGPSWindow

        self.show()

    def select_file(self):
        """
        Se define un metodo para la eleccion de un archivo de audio existente

        """
        self.audio_mod.stop_rec()
        file_path = str(QFileDialog.getOpenFileName(self, "Elegir archivo"))
        if file_path != "":
            if file_path.endswith(".wav"):
                self.path_label.setText(file_path)
                self.path_label.resize(self.path_label.minimumSizeHint())
                self.audio_mod.load_file(file_path)
            else:
                self.wrong_file_box.exec_()

    def rec_file_save(self):
        """
        Metodo para almacenar el archivo que fue grabado en la etapa de grabacion

        """
        file_path = str(QFileDialog.getSaveFileName(self, 'Guardar archivo'))
        if file_path != "" and not self.audio_mod.save_rec(file_path):
            self.no_data_box.exec_()

    def out_file_save(self):
        """
        Metodo para almacenar el archivo que fue procesado en la etapa de salida

        """
        file_path = str(QFileDialog.getSaveFileName(self, 'Guardar archivo'))
        recorded = self.input_output[PROCESS_GROUP] == "Grabacion"
        tfs = TRANSFER_FUNCTIONS[self.input_output[
            INPUT_GROUP]] + TRANSFER_FUNCTIONS[self.input_output[OUTPUT_GROUP]]
        if file_path != "" and not self.audio_mod.save_out(
                file_path, recorded, *tfs):
            self.no_data_box.exec_()

    def out_file_play(self):
        """
        Metodo para reproducir el archivo que fue procesado en la etapa de salida

        """
        tfs = TRANSFER_FUNCTIONS[self.input_output[
            INPUT_GROUP]] + TRANSFER_FUNCTIONS[self.input_output[OUTPUT_GROUP]]
        self.audio_mod.play_out(
            self.input_output[PROCESS_GROUP] == "Grabacion", *tfs)

    def closeEvent(self, event):
        """
        Metodo para cerrar la ventana principal

        """
        # Overwriten method from parent QWidget. QWidget -> QMainWindow -> EGPSWindow
        event.ignore()
        if self.msg_box.exec_() == QMessageBox.AcceptRole:
            sys.exit()

    def radio_button_clicked(self, text_option, group_option):
        self.input_output[group_option] = text_option
        print(str(self.input_output))

#-----------------------------------------------------------------------------------------------------------------------

    """Creacion de labels, pushbuttons y radiobuttons"""
    def create_label(self, name, pos_x, pos_y):
        """
        Se define un metodo para la creacion de los labels de la interfaz grafica
        :param name: Nombre del label
        :param pos_x: Posicion horizontal
        :param pos_y: Posicion vertical

        """
        label = QLabel(name, self)
        label.move(pos_x, pos_y)
        label.resize(label.minimumSizeHint())

    def define_push_button(self,
                           text,
                           pos_x,
                           pos_y,
                           callback,
                           image_path=None,
                           resize=False):
        """
        Se define un metodo para la creacion de push buttons en la interfaz grafica

        :param text: Texto que muestra el pushbutton
        :param pos_x: Posicion horizontal
        :param pos_y: Posicion Vertical
        :param callback:
        :param image_path: Ruta del icono o imagen asociada al push button
        :param resize: Cambia el tamano del pushbutton
        :return:
        """
        btn = QPushButton(text, self)
        btn.move(pos_x, pos_y)
        if image_path:
            btn.setIcon(QIcon(image_path))
        if resize:
            btn.resize(btn.minimumSizeHint())
        # This binds the signal clicked() from the button to the callback.
        self.connect(btn, SIGNAL("clicked()"), callback)

    def create_radio_button(self, text, pos_x, pos_y, group, button_group):
        """
        Se define un metodo para la creacion de radio buttons

        :param text: Texto que acompana al radio button
        :param pos_x: Posicion horizontal
        :param pos_y: Posicion vertical
        :param group:
        :param button_group:
        :return:
        """
        radio_button = QRadioButton(text, self)
        radio_button.move(pos_x, pos_y)
        # This binds the signal pressed() from the radio button to the radio_button_clicked method.
        self.connect(radio_button, SIGNAL("pressed()"),
                     partial(self.radio_button_clicked, text, group))
        radio_button.resize(radio_button.minimumSizeHint())
        button_group.addButton(radio_button)
Exemplo n.º 26
0
class MainWindow(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.__timer = QTimer(self)
        self.background = QLabel(self)
        self.background.setPixmap(QPixmap(get_asset_path(["background.png"])))
        self.__entities = []
        self.__team_1_label = QLabel("Gold Team 1: 0", self)
        self.__team_1_label.setSizePolicy(QSizePolicy.Ignored,
                                          QSizePolicy.Ignored)
        # self.__team_1_label.setFixedWidth(600)
        self.__font = QFont("", 20)
        self.__font.setBold(True)
        self.__team_1_label.setStyleSheet("color: yellow;")
        self.__team_1_label.setFont(self.__font)
        self.__team_2_label = QLabel("Gold Team 2: 0", self)
        self.__team_2_label.setStyleSheet("color: yellow;")
        self.__team_2_label.setFont(self.__font)
        # self.__team_2_label.setFixedWidth(600)
        self.__team_2_label.move(
            self.width() - self.__team_2_label.sizeHint().width(), 0)
        self.__objective_label = QLabel("Objective: None", self)
        self.__font_objective = QFont("", 15)
        self.__font_objective.setBold(True)
        self.__objective_label.setFont(self.__font_objective)
        self.__objective_label.move(
            self.width() // 2 - self.__objective_label.sizeHint().width() // 2,
            0)

    def startMain(self, main, delay=25):
        self.__timer.timeout.connect(main)
        self.__timer.start(delay)

    def add_entity(self, entity):
        entity.setParent(self)
        entity.show()
        self.__entities.append(entity)

    def set_gold_t1(self, gold):
        self.__team_1_label.setText("Gold Team 1: {}".format(gold))
        self.__team_1_label.setFixedWidth(
            self.__team_1_label.sizeHint().width())

    def set_gold_t2(self, gold):
        self.__team_2_label.setText("Gold Team 2: {}".format(gold))
        self.__team_2_label.setFixedWidth(
            self.__team_2_label.sizeHint().width())
        self.__team_2_label.move(
            self.width() - self.__team_2_label.sizeHint().width(), 0)

    def set_objective(self, objective):
        self.__objective_label.setText("Objective: {}".format(objective))
        self.__objective_label.move(
            self.width() // 2 - self.__objective_label.sizeHint().width() // 2,
            0)

    def keyPressEvent(self, e):
        if e.key() == Qt.Key_Space:
            print(len(self.__entities))
            print("Testing")

    def setFixedSize(self, *__args):
        super().setFixedSize(*__args)
        self.__team_2_label.move(
            self.width() - self.__team_2_label.sizeHint().width(), 0)
        self.__objective_label.move(
            self.width() // 2 - self.__objective_label.sizeHint().width() // 2,
            0)
Exemplo n.º 27
0
class Panel(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.clean_up_queue = []
        self.summoner = SummonerData()
        self.summoner.getStaticData()

        ### Search Bar ###
        ##################

        #label
        self.search_label = QLabel(self)
        self.search_label.move(20, 15)
        self.search_label.resize(220, 25)
        self.search_label.setText('Enter summoner name(s):')
        self.search_label.setStyleSheet("QLabel {font:14pt}")

        #text field
        self.search_field = QLineEdit(self)
        self.search_field.move(260, 15)
        self.search_field.resize(250, 25)
        self.search_field.setPlaceholderText("ex: mcnuggets, teltor, ...")
        self.search_field.setFocusPolicy(Qt.ClickFocus)

        #search button
        self.search_button = QPushButton(self)
        self.search_button.move(520, 15)
        self.search_button.resize(150, 25)
        self.search_button.setText('Search Summoner')

        #region combobox
        self.region_list = QComboBox(self)
        self.region_list.move(680, 15)
        self.region_list.resize(75, 25)
        regions = ['NA', 'LAN', 'BR', 'LAS', 'EUW', 'EUNE', 'TR', 'RU', 'OCE']
        self.region_list.addItems(regions)

        #error label
        self.error_label = QLabel(self)
        self.error_label.move(775, 15)
        self.error_label.resize(160, 25)
        self.error_label.setStyleSheet("QLabel {font:14pt}")

        ### Summoner Information ###
        ############################

        #summoner Icon label
        self.icon_label = QLabel(self)
        self.icon_label.setScaledContents(True)
        self.icon_label.move(260, 50)
        self.icon_label.resize(110, 110)

        #name label
        self.name_label = QLabel(self)
        self.name_label.move(380, 50)
        self.name_label.resize(620, 50)
        self.name_label.setText('SUMMONER NAME')
        self.name_label.setStyleSheet("QLabel {font:32pt}")

        #rank label
        self.rank_label = QLabel(self)
        self.rank_label.move(380, 100)
        self.rank_label.resize(200, 60)
        self.rank_label.setText('summoner rank')
        self.rank_label.setStyleSheet("QLabel {font:18pt}")

        #miniseries labels
        self.series_labels = {}
        self.pixmap_win = QPixmap()
        self.pixmap_loss = QPixmap()
        self.pixmap_n = QPixmap()
        self.pixmap_win.load("./images/win.png")
        self.pixmap_loss.load("./images/loss.png")
        self.pixmap_n.load("./images/n.png")
        xPos = 600
        for x in range(5):
            match_label = QLabel(self)
            match_label.move(xPos, 120)
            match_label.resize(35, 35)
            match_label.setScaledContents(True)
            match_label.hide()
            self.series_labels[x] = match_label
            xPos += 40

        #mastery image labels
        print 'loading mastery images ...'
        self.ferocity_tree_images = self.getMasteryImages(
            self.summoner.ferocityMasteryTree())
        self.cunning_tree_images = self.getMasteryImages(
            self.summoner.cunningMasteryTree())
        self.resolve_tree_images = self.getMasteryImages(
            self.summoner.resolveMasteryTree())
        print 'Done'

        #champion icon image labels
        print 'loading champion icon images ...'
        self.championIcons = self.getChampionIconImages(
            self.summoner.championList())
        print 'Done'

        #overview widget
        self.overview_widget = QWidget()
        self.overview_menu = QTabWidget(self.overview_widget)
        self.overview_menu.resize(720, 270)

        #runes widget
        self.runes_widget = QWidget()
        self.runes_menu = QTabWidget(self.runes_widget)
        self.runes_menu.resize(720, 270)

        #masteries widget
        self.masteries_widget = QWidget()
        self.masteries_menu = QTabWidget(self.masteries_widget)
        self.masteries_menu.resize(720, 270)

        #summoner menu
        self.menu = QTabWidget(self)
        self.menu.move(260, 180)
        self.menu.resize(720, 300)
        self.menu.addTab(self.overview_widget, "Overview")
        self.menu.addTab(self.runes_widget, "Runes")
        self.menu.addTab(self.masteries_widget, "Masteries")
        self.menu.hide()

        #summoners buttons
        self.button_list = {}
        yPos = 150
        for x in range(10):
            sum_button = QPushButton(self)
            sum_button.move(50, yPos)
            sum_button.resize(150, 25)
            sum_button.hide()
            self.button_list[x] = sum_button
            yPos += 25

        ### Connecting Widgets ###
        ##########################

        self.connect(self.search_button, QtCore.SIGNAL("clicked()"),
                     self.getData)
        self.connect(self.search_button, QtCore.SIGNAL("clicked()"),
                     self.getRankedData)
        self.connect(self.button_list[0], QtCore.SIGNAL("clicked()"),
                     lambda: self.displayData(str(self.button_list[0].text())))
        self.connect(self.button_list[1], QtCore.SIGNAL("clicked()"),
                     lambda: self.displayData(str(self.button_list[1].text())))
        self.connect(self.button_list[2], QtCore.SIGNAL("clicked()"),
                     lambda: self.displayData(str(self.button_list[2].text())))
        self.connect(self.button_list[3], QtCore.SIGNAL("clicked()"),
                     lambda: self.displayData(str(self.button_list[3].text())))
        self.connect(self.button_list[4], QtCore.SIGNAL("clicked()"),
                     lambda: self.displayData(str(self.button_list[4].text())))
        self.connect(self.button_list[5], QtCore.SIGNAL("clicked()"),
                     lambda: self.displayData(str(self.button_list[5].text())))
        self.connect(self.button_list[6], QtCore.SIGNAL("clicked()"),
                     lambda: self.displayData(str(self.button_list[6].text())))
        self.connect(self.button_list[7], QtCore.SIGNAL("clicked()"),
                     lambda: self.displayData(str(self.button_list[7].text())))
        self.connect(self.button_list[8], QtCore.SIGNAL("clicked()"),
                     lambda: self.displayData(str(self.button_list[8].text())))
        self.connect(self.button_list[9], QtCore.SIGNAL("clicked()"),
                     lambda: self.displayData(str(self.button_list[9].text())))

        ### Window Configuration ###
        ############################

        #window settings
        self.setGeometry(200, 150, 1000, 500)
        self.setMaximumSize(1000, 500)
        self.setWindowTitle('summoner App')

        self.show()

    ### GUI methods ###
    ###################

    ############### GUI get methods ###############

    #get data related to given summoner names
    def getData(self):
        self.cleanUp()
        name_list = str(self.search_field.text()).replace(
            ' ', '').lower().split(',')
        region = str(self.region_list.currentText()).lower()
        if name_list != ['']:
            try:
                self.summoner.getSummonerData(name_list, region)
                for x in range(len(name_list)):
                    sum_name = self.summoner.getName(name_list[x])
                    if sum_name != None:
                        self.button_list[x].setText(sum_name)
                        self.clean_up_queue.append(self.button_list[x])
                    else:
                        self.button_list[x].setText(name_list[x])
                        self.clean_up_queue.append(self.button_list[x])
                        self.button_list[x].setEnabled(False)
                    self.button_list[x].show()
            except RiotError as e:
                response = e.message
                print response
                if response == 'ServiceUnavailable':
                    self.error_label.setText(response)
                elif response == '429':
                    self.error_label.setText('Rate limit reached')
                elif response == 'InternalServerError':
                    self.error_label.setText(response)
                elif response == 'Unauthorized':
                    self.error_label.setText('Invalid Input')
                elif response == 'ServerError':
                    self.error_label.setText(response)
                else:
                    self.error_label.setText('Not Found')
            except KeyError as k:
                self.error_label.setText('Invalid Input')

    #get summoner ranked data
    def getRankedData(self):
        if str(self.search_field.text()) != '':
            region = str(self.region_list.currentText()).lower()
            try:
                self.summoner.getRankedData(region)
            except RiotError:
                print 'Rank info not found'

    #get mastery images
    def getMasteryImages(self, masteryList):
        pixmap_list = collections.OrderedDict()
        empty_spaces = 0
        for row in masteryList:
            if len(row['masteryTreeItems']) == 2:
                #if len(row) == 3:
                row['masteryTreeItems'].append(None)
                #row.append(None)
            for element in row['masteryTreeItems']:
                #for element in row:
                if element != None:
                    pixmap = QPixmap()
                    pixmap.loadFromData(
                        self.summoner.getImage(
                            'mastery',
                            str(element['masteryId']) + '.png'))
                    pixmap_list[element['masteryId']] = pixmap
                else:
                    pixmap_list['null' + str(empty_spaces)] = None
                    empty_spaces += 1
        return pixmap_list

    #get champion icon images
    def getChampionIconImages(self, clist):
        pixmap_list = {}
        for champ in clist.values():
            pixmap = QPixmap()
            pixmap.loadFromData(
                self.summoner.getImage('champion', champ['key'] + '.png'))
            pixmap_list[champ['name']] = pixmap
        return pixmap_list

    ############### GUI update methods ###############

    #removes previous data from GUI
    def cleanUp(self):
        self.error_label.setText("")
        #clears summoner info
        self.icon_label.setPixmap(QPixmap())
        self.icon_label.setStyleSheet("QLabel {}")
        self.name_label.setText("")
        self.rank_label.setText("")
        #hides elements in clean up queue
        for x in self.clean_up_queue:
            x.hide()
            x.setEnabled(True)

    #display data
    def displayData(self, buttonName):
        sum_ID = self.summoner.getID(buttonName)
        self.displayIcon(buttonName.replace(' ', '').lower())
        self.name_label.setText(buttonName)
        self.displayRank(sum_ID)
        self.displayMenu(sum_ID)

    #display summoner icon
    def displayIcon(self, summoner_name):
        iconName = self.summoner.getIcon(summoner_name)
        iconPixmap = QPixmap()
        self.icon_label.setStyleSheet(
            "QLabel {border-style: outset; border-width: 3px; border-color: gold}"
        )
        try:
            iconPixmap.loadFromData(
                self.summoner.getImage('profileicon', iconName))
            self.icon_label.setPixmap(iconPixmap)
        except RiotError:
            iconPixmap.load("./images/no_image.png")
            self.icon_label.setPixmap(iconPixmap)

    #display summoner rank
    def displayRank(self, sumID):
        for x in range(len(self.series_labels)):
            self.series_labels[x].setPixmap(QPixmap())
        try:
            tier = self.summoner.getTier(sumID)
            division = self.summoner.getDivision(sumID)
            points = self.summoner.getLeaguePoints(sumID)
            self.rank_label.setText(tier + ': ' + division + '\n' +
                                    str(points) + ' league points')
            if points == 100:
                self.displayMiniseries(sumID)
        except KeyError:
            self.rank_label.setText('UNRANKED')

    #display promotion series
    def displayMiniseries(self, sumID):
        progress = self.summoner.getRankSeries(sumID)
        i = 0
        for x in progress:
            if x == 'W':
                self.series_labels[i].setPixmap(self.pixmap_win)
            elif x == 'L':
                self.series_labels[i].setPixmap(self.pixmap_loss)
            else:
                self.series_labels[i].setPixmap(self.pixmap_n)
            self.clean_up_queue.append(self.series_labels[i])
            self.series_labels[i].show()
            i += 1

    #display summoner menu
    def displayMenu(self, sumID):
        self.displayOverviewMenu(sumID)
        self.displayRuneMenu(sumID)
        self.displayMasteryMenu(sumID)
        self.clean_up_queue.append(self.menu)
        self.menu.show()

    #display overview menu
    def displayOverviewMenu(self, sumID):
        self.overview_menu.clear()

        overview_normal = OverviewWidget()
        overview_ranked_solo = OverviewWidget()
        overview_ranked_team = OverviewWidget()
        overview_champions = ChampionsWidget()

        overview_normal.showStats(self.summoner.getStats(sumID, 'Normal'))
        overview_ranked_solo.showStats(
            self.summoner.getStats(sumID, 'Ranked Solo'))
        overview_ranked_team.showStats(
            self.summoner.getStats(sumID, 'Ranked Team'))
        overview_champions.showStats(self.summoner.getChampionStats(sumID),
                                     self.championIcons)

        self.overview_menu.addTab(overview_normal, 'Normal')
        self.overview_menu.addTab(overview_ranked_solo, 'Ranked Solo')
        self.overview_menu.addTab(overview_ranked_team, 'Ranked Team')
        self.overview_menu.addTab(overview_champions, 'Champions')

    #display rune menu
    def displayRuneMenu(self, sumID):
        self.runes_menu.clear()
        for x in range(self.summoner.getNumOfRunePages(sumID)):
            rune_page = RuneWidget()
            rune_page.setSize(700, 225)
            rune_page.setName(self.summoner.getRunePageName(sumID, x))
            rune_data = self.summoner.getRunes(sumID, x)
            if rune_data != None:
                for y in rune_data:
                    rid = self.summoner.getRuneID(y)
                    desc = self.summoner.runeDescription(rid)
                    rname = self.summoner.runeName(rid)
                    rune_page.addRune(rid, desc, rname)
                rune_page.showRunes()
            self.runes_menu.addTab(rune_page, str(x + 1))

    #display mastery menu
    def displayMasteryMenu(self, sumID):
        self.masteries_menu.clear()
        for x in range(self.summoner.getNumOfMasteryPages(sumID)):
            mastery_page = MasteryWidget()
            mastery_page.setMasteryLabels(self.ferocity_tree_images,
                                          self.cunning_tree_images,
                                          self.resolve_tree_images)
            mastery_page.setName(self.summoner.getMasteryPageName(sumID, x))
            mastery_data = self.summoner.getMasteries(sumID, x)
            if mastery_data != None:
                for y in mastery_data:
                    mid = self.summoner.getMasteryID(y)
                    rank = self.summoner.getMasteryRank(y)
                    mastery_page.setMasteryRank(mid, rank)
            mastery_page.setTotalPoints()
            self.masteries_menu.addTab(mastery_page, str(x + 1))
Exemplo n.º 28
0
class MyMainWindow(QMainWindow):
    ' Main Window '
    def __init__(self, parent=None):
        super(MyMainWindow, self).__init__(parent)
        self.statusBar().showMessage(__doc__)
        self.setWindowTitle(__doc__)
        self.setMinimumSize(250, 280)
        self.setMaximumSize(300, 300)
        self.resize(250, 290)
        self.setWindowIcon(QIcon.fromTheme("face-monkey"))
        self.setStyleSheet('''QWidget { color: rgba( 0, 255, 255, 255 );
            background-color: #323232; font-family: 'Ubuntu Light';
            font-size: 14px;
            }

            QToolTip {
                border: 1px solid black;
                background-color: #ffa02f;
                background-image: None;
                padding: 1px;
                border-radius: 3px;
                opacity: 100;
            }

            QWidget:item:hover {
                background-color: QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #ffa02f,
                    stop: 1 #ca0619
                );
                color: #000000;
            }

            QWidget:item:selected {
                background-color: QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #ffa02f,
                    stop: 1 #d7801a
                );
            }

            QWidget:disabled {
                color: #404040;
                background-color: #323232;
            }

            QWidget:focus {
                background-image: None;
                border: 2px solid QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #ffa02f,
                    stop: 1 #d7801a
                );
            }

            QPushButton {
                background-color: QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #565656,
                    stop: 0.1 #525252,
                    stop: 0.5 #4e4e4e,
                    stop: 0.9 #4a4a4a,
                    stop: 1 #464646
                );
                border-width: 1px;
                border-color: #1e1e1e;
                border-style: solid;
                border-radius: 6;
                padding: 3px;
                font-size: 12px;
                padding-left: 5px;
                padding-right: 5px;
                background-image: None;
            }

            QPushButton:pressed {
                background-image: None;
                background-color: QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #2d2d2d,
                    stop: 0.1 #2b2b2b,
                    stop: 0.5 #292929,
                    stop: 0.9 #282828,
                    stop: 1 #252525
                );
            }

            QComboBox {
                background-image: None;
                selection-background-color: #ffaa00;
                background-color: QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #565656,
                    stop: 0.1 #525252,
                    stop: 0.5 #4e4e4e,
                    stop: 0.9 #4a4a4a,
                    stop: 1 #464646
                );
                border-style: solid;
                border: 1px solid #1e1e1e;
                border-radius: 5;
            }

            QComboBox:hover, QPushButton:hover {
                background-image: url(.bg.png);
                border: 2px solid QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #ffa02f,
                    stop: 1 #d7801a
                );
            }

            QComboBox:on {
                padding-top: 3px;
                padding-left: 4px;
                background-color: QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #2d2d2d,
                    stop: 0.1 #2b2b2b,
                    stop: 0.5 #292929,
                    stop: 0.9 #282828,
                    stop: 1 #252525
                );
                selection-background-color: #ffaa00;
                background-image: None;
            }

            QComboBox QAbstractItemView {
                background-image: None;
                border: 2px solid darkgray;
                selection-background-color: QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #ffa02f,
                    stop: 1 #d7801a
                );
            }

            QComboBox::drop-down {
                 subcontrol-origin: padding;
                 subcontrol-position: top right;
                 width: 15px;
                 border-left-width: 0px;
                 border-left-color: darkgray;
                 border-left-style: solid;
                 border-top-right-radius: 3px;
                 border-bottom-right-radius: 3px;
                 background-image: None;
             }

            QComboBox::down-arrow { background-image: None; }

            QSlider {
                border-width: 2px;
                border-color: #1e1e1e;
                border-style: solid;
                padding: 3px;
                font-size: 8px;
                padding-left: 5px;
                padding-right: 5px;
                width: 25px;
                border-radius: 5px;
            }

            QSlider::sub-page:vertical {
                background: red;
                border: none;
                width: 25px;
            }

            QSlider::add-page:vertical {
                background: green;
                border: none;
                width: 25px;
            }

            QSlider::handle:vertical {
                background-color: QLinearGradient(spread:pad, x1:0, y1:0, x2:1,
                    y2:0.273, stop:0 rgba(0, 0, 0, 255),
                    stop:1 rgba(150, 255, 255, 255)
                    );
                width: 10px;
                height: 25px;
                border: 1px solid grey;
                text-align: center;
                border-top-left-radius: 2px;
                border-bottom-left-radius: 2px;
                border-top-right-radius: 2px;
                border-bottom-right-radius 2px;
                margin-left: 2px;
                margin-right: 2px;
            }

            QSlider::handle:vertical:hover {
                border: 2px solid #ffaa00;
                margin-left: 2px;
                margin-right: 2px;
            }

            QSlider::sub-page:vertical:disabled {
                background: #bbb;
                border-color: #999;
            }

            QSlider::add-page:vertical:disabled {
                background: #eee;
                border-color: #999;
            }

            QSlider::handle:vertical:disabled {
                background: #eee;
                border: 1px solid #aaa;
                border-radius: 4px;
            } ''')

        self.label1 = QLabel(self)
        self.label1.setText('Use Debug')
        self.label1.setGeometry(QtCore.QRect(25, 25, 125, 25))

        self.slider1 = QSlider(self)
        self.slider1.setGeometry(QtCore.QRect(150, 25, 25, 25))
        self.slider1.setTickInterval(1)
        self.slider1.setCursor(QCursor(QtCore.Qt.OpenHandCursor))
        self.slider1.TickPosition(QSlider.TicksBothSides)
        self.slider1.setRange(0, 1)
        self.slider1.setValue(1)
        self.sli1lbl = QLabel(str(self.slider1.value()), self.slider1)
        self.sli1lbl.move(9, 5)
        self.sli1lbl.setAutoFillBackground(False)
        self.slider1.valueChanged.connect(
            lambda: self.sli1lbl.setText(str(self.slider1.value())))
        self.slider1.sliderPressed.connect(
            lambda: self.slider1.setCursor(QCursor(QtCore.Qt.ClosedHandCursor)))
        self.slider1.sliderReleased.connect(
            lambda: self.slider1.setCursor(QCursor(QtCore.Qt.OpenHandCursor)))

        self.label2 = QLabel(self)
        self.label2.setText('Make Executable')
        self.label2.setGeometry(QtCore.QRect(25, 75, 125, 25))

        self.slider2 = QSlider(self)
        self.slider2.setGeometry(QtCore.QRect(150, 75, 25, 25))
        self.slider2.setTickInterval(1)
        self.slider2.setCursor(QCursor(QtCore.Qt.OpenHandCursor))
        self.slider2.TickPosition(QSlider.TicksBothSides)
        self.slider2.setRange(0, 1)
        self.slider2.setValue(1)
        self.sli2lbl = QLabel(str(self.slider2.value()), self.slider2)
        self.sli2lbl.move(9, 5)
        self.sli2lbl.setAutoFillBackground(False)
        self.slider2.valueChanged.connect(
            lambda: self.sli2lbl.setText(str(self.slider2.value())))
        self.slider2.sliderPressed.connect(
            lambda: self.slider2.setCursor(QCursor(QtCore.Qt.ClosedHandCursor)))
        self.slider2.sliderReleased.connect(
            lambda: self.slider2.setCursor(QCursor(QtCore.Qt.OpenHandCursor)))

        self.label3 = QLabel(self)
        self.label3.setText('Relative Imports')
        self.label3.setGeometry(QtCore.QRect(25, 125, 125, 25))

        self.slider3 = QSlider(self)
        self.slider3.setGeometry(QtCore.QRect(150, 125, 25, 25))
        self.slider3.setTickInterval(1)
        self.slider3.setCursor(QCursor(QtCore.Qt.OpenHandCursor))
        self.slider3.TickPosition(QSlider.TicksBothSides)
        self.slider3.setRange(0, 1)
        self.slider3.setValue(0)
        self.sli3lbl = QLabel(str(self.slider3.value()), self.slider3)
        self.sli3lbl.move(9, 5)
        self.sli3lbl.setAutoFillBackground(False)
        self.slider3.valueChanged.connect(
            lambda: self.sli3lbl.setText(str(self.slider3.value())))
        self.slider3.sliderPressed.connect(
            lambda: self.slider3.setCursor(QCursor(QtCore.Qt.ClosedHandCursor)))
        self.slider3.sliderReleased.connect(
            lambda: self.slider3.setCursor(QCursor(QtCore.Qt.OpenHandCursor)))

        self.label4 = QLabel(self)
        self.label4.setText('Indent Spaces')
        self.label4.setGeometry(QtCore.QRect(25, 175, 125, 25))

        self.combo1 = QComboBox(self)
        self.combo1.setCursor(QCursor(QtCore.Qt.PointingHandCursor))
        self.combo1.addItems(['4', '0', '2', '6', '8'])
        self.combo1.setGeometry(QtCore.QRect(150, 175, 50, 25))

        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setGeometry(QtCore.QRect(25, 225, 200, 32))
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel |
            QDialogButtonBox.Close | QDialogButtonBox.Help)
        self.buttonBox.setCenterButtons(False)
        self.buttonBox.helpRequested.connect(lambda: QMessageBox.about(
            self, __doc__, str(__doc__ + ', ' + ',\nversion ' + __version__ +
                               '(' + __license__ + '),\nby ' + __author__ + ', '
                               + __email__)))
        self.buttonBox.accepted.connect(self.run)
        self.buttonBox.rejected.connect(self.close)
        palette = self.palette()
        palette.setBrush(QPalette.Base, Qt.transparent)
        self.setPalette(palette)
        self.setAttribute(Qt.WA_OpaquePaintEvent, False)

    def run(self):
        'Run the actual conversion.'
        # Ask the User for the source .ui file as input
        filein = str(QFileDialog.getOpenFileName(
            self, __doc__, path.expanduser("~"), 'UI(*.ui)')).strip()
        # Parse Value of Slider1 as the Debug flag parameter
        if self.slider1.value() == 0:
            arg1 = ''
        else:
            arg1 = '--debug '
        # Parse Value of Slider2 as the Execute flag parameter
        if self.slider2.value() == 0:
            arg2 = ''
        else:
            arg2 = '--execute '
        # Parse Value of Slider3 as the relative imports flag parameter
        if self.slider3.value() == 0:
            arg3 = ''
        else:
            arg3 = '--from-imports '
        # debug
        #print(arg1, arg2, arg3, str(self.combo1.currentText()))
        # run the subprocesses
        subprocess.Popen(
            'nice --adjustment=19 pyuic4 ' + arg1 + arg2 + arg3 +
            '--indent=' + str(self.combo1.currentText()) +
            ' --output=' + str(filein).lower().replace('.ui', '.py') +
            ' ' + filein +
            ' && chmod -v +x ' + str(filein).lower().replace('.ui', '.py'),
            shell=True)

    def paintEvent(self, event):
        ' Paint semi-transparent background '
        painter = QPainter(self)
        painter.fillRect(event.rect(), Qt.transparent)
        painter.setPen(Qt.NoPen)
        painter.setBrush(QColor(0, 0, 0))
        painter.setOpacity(0.75)
        painter.drawRoundedRect(self.rect(), 75, 50)
        painter.end()
Exemplo n.º 29
0
from PyQt4.QtGui import QApplication, QLabel, QPixmap

app = QApplication([])

label = QLabel()
pixmap = QPixmap("images/reeborg.png")
label.setPixmap(pixmap)
label.move(10, 10)
label.show()

label2 = QLabel()
pixmap = QPixmap("images/python.jpg")
label2.setPixmap(pixmap)
label2.move(200, 10)
label2.show()

app.exec_()

app.quit()
Exemplo n.º 30
0
class Window(QWidget):
   def __init__(self):
      QWidget.__init__(self)
      
      self.factorValue = 1
      
      #Window Sizing
      self.setFixedSize(600, 400)
      self.setWindowTitle("IME 314 Tool")
      
      '''Start Top Panel'''
      #Interest label
      self.interest = QLabel('i: ', self)
      self.interest.move(200, 10)
      
      #Period label
      self.period = QLabel('n: ', self)
      self.period.move(350, 10)

      #Interest text box
      self.interestEdit = QLineEdit(self)
      self.interestEdit.setFixedWidth(40)
      self.interestEdit.setSizePolicy(QSizePolicy.Fixed,
                                 QSizePolicy.Fixed)
      self.interestEdit.move(220, 10)
      
      #Period text box
      self.periodEdit = QLineEdit(self)
      self.periodEdit.setFixedWidth(30)
      self.periodEdit.setSizePolicy(QSizePolicy.Fixed,
                                 QSizePolicy.Fixed)
      self.periodEdit.move(370, 10)
      
      #Multiplier Label
      self.multiplier = QLabel('Multiplier Value: ', self)
      self.multiplier.move(80, 50)
      
      #Multiplier text box
      self.multiplierEdit = QLineEdit(self)
      self.multiplierEdit.setFixedWidth(100)
      self.multiplierEdit.setSizePolicy(QSizePolicy.Fixed,
                                 QSizePolicy.Fixed)
      self.multiplierEdit.move(160, 50)
      
      #Final Value Label
      self.finalValue = QLabel('Final Value: ', self)
      self.finalValue.move(370, 50)
      
      #Final Value text box
      self.finalValueEdit = QLineEdit(self)
      self.finalValueEdit.setFixedWidth(100)
      self.finalValueEdit.setSizePolicy(QSizePolicy.Fixed,
                                 QSizePolicy.Fixed)
      self.finalValueEdit.move(440, 50)
      '''End Top Panel'''
      
      '''Start Column 1'''
      #F/P button
      self.FoPButton = QPushButton('F/P (P->F)', self)
      self.FoPButton.setFixedSize(70, 30)
      self.FoPButton.move(70, 110)
      self.FoPButton.clicked.connect(self.show_FoP)
      
      #F/P text box
      self.FoPButtonEdit = QLineEdit(self)
      self.FoPButtonEdit.setFixedWidth(100)
      self.FoPButtonEdit.setSizePolicy(QSizePolicy.Fixed,
                                 QSizePolicy.Fixed)
      self.FoPButtonEdit.move(160, 115)
      
      #A/P button
      self.AoPButton = QPushButton('A/P (P->A)', self)
      self.AoPButton.setFixedSize(70, 30)
      self.AoPButton.move(70, 170)
      self.AoPButton.clicked.connect(self.show_AoP)
      
      #A/P text box
      self.AoPButtonEdit = QLineEdit(self)
      self.AoPButtonEdit.setFixedWidth(100)
      self.AoPButtonEdit.setSizePolicy(QSizePolicy.Fixed,
                                 QSizePolicy.Fixed)
      self.AoPButtonEdit.move(160, 175)
      
      #F/A button
      self.FoAButton = QPushButton('F/A (A->F)', self)
      self.FoAButton.setFixedSize(70, 30)
      self.FoAButton.move(70, 230)
      self.FoAButton.clicked.connect(self.show_FoA)

      #F/A text box
      self.FoAButtonEdit = QLineEdit(self)
      self.FoAButtonEdit.setFixedWidth(100)
      self.FoAButtonEdit.setSizePolicy(QSizePolicy.Fixed,
                                 QSizePolicy.Fixed)
      self.FoAButtonEdit.move(160, 235)
      
      #A/G button
      self.AoGButton = QPushButton('A/G (G->A)', self)
      self.AoGButton.setFixedSize(70, 30)
      self.AoGButton.move(70, 290)
      self.AoGButton.clicked.connect(self.show_AoG)
      
      #A/G text box
      self.AoGButtonEdit = QLineEdit(self)
      self.AoGButtonEdit.setFixedWidth(100)
      self.AoGButtonEdit.setSizePolicy(QSizePolicy.Fixed,
                                 QSizePolicy.Fixed)
      self.AoGButtonEdit.move(160, 295)
      '''End Column 1'''
      
      '''Start Column 2'''
      #P/F button
      self.PoFButton = QPushButton('P/F (F->P)', self)
      self.PoFButton.setFixedSize(70, 30)
      self.PoFButton.move(350, 110)
      self.PoFButton.clicked.connect(self.show_PoF)
      
      #P/F text box
      self.PoFButtonEdit = QLineEdit(self)
      self.PoFButtonEdit.setFixedWidth(100)
      self.PoFButtonEdit.setSizePolicy(QSizePolicy.Fixed,
                                 QSizePolicy.Fixed)
      self.PoFButtonEdit.move(440, 115)
      
      #P/A button
      self.PoAButton = QPushButton('P/A (A->P)', self)
      self.PoAButton.setFixedSize(70, 30)
      self.PoAButton.move(350, 170)
      self.PoAButton.clicked.connect(self.show_PoA)
      
      #P/A text box
      self.PoAButtonEdit = QLineEdit(self)
      self.PoAButtonEdit.setFixedWidth(100)
      self.PoAButtonEdit.setSizePolicy(QSizePolicy.Fixed,
                                 QSizePolicy.Fixed)
      self.PoAButtonEdit.move(440, 175)
      
      #A/F button
      self.AoFButton = QPushButton('A/F (F->A)', self)
      self.AoFButton.setFixedSize(70, 30)
      self.AoFButton.move(350, 230)
      self.AoFButton.clicked.connect(self.show_AoF)
      
      #A/F text box
      self.AoFButtonEdit = QLineEdit(self)
      self.AoFButtonEdit.setFixedWidth(100)
      self.AoFButtonEdit.setSizePolicy(QSizePolicy.Fixed,
                                 QSizePolicy.Fixed)
      self.AoFButtonEdit.move(440, 235)
      
      #A/G button
      self.PoGButton = QPushButton('P/G (G->P)', self)
      self.PoGButton.setFixedSize(70, 30)
      self.PoGButton.move(350, 290)
      self.PoGButton.clicked.connect(self.show_PoG)
      
      #A/G text box
      self.PoGButtonEdit = QLineEdit(self)
      self.PoGButtonEdit.setFixedWidth(100)
      self.PoGButtonEdit.setSizePolicy(QSizePolicy.Fixed,
                                 QSizePolicy.Fixed)
      self.PoGButtonEdit.move(440, 295)
      '''End Column 2'''
      
      #Running Sum Label
      self.sumValue = QLabel('Sum: ', self)
      self.sumValue.move(130, 360)
      
      #Final Value text box
      self.sumEdit = QLineEdit(self)
      self.sumEdit.setFixedWidth(100)
      self.sumEdit.setSizePolicy(QSizePolicy.Fixed,
                                 QSizePolicy.Fixed)
      self.sumEdit.move(160, 355)
      
      #Clear button
      self.clearButton = QPushButton('Clear', self)
      self.clearButton.setFixedSize(50, 30)
      self.clearButton.move(350, 350)
      self.clearButton.clicked.connect(self.clear_sum)
      
      #Clear all button
      self.clearAllButton = QPushButton('Clear All', self)
      self.clearAllButton.setFixedSize(50, 30)
      self.clearAllButton.move(430, 350)
      self.clearAllButton.clicked.connect(self.clear_values)
      
      #Author label
      self.author = QLabel("Created by: " + __author__, self)
      self.author.move(455, 385)
      
      #List of all editable fields
      self.fields = [self.sumEdit, self.finalValueEdit, self.interestEdit,
                     self.periodEdit, self.multiplierEdit, self.sumEdit,
                     self.FoPButtonEdit, self.AoPButtonEdit, self.FoAButtonEdit,
                     self.AoGButtonEdit, self.PoFButtonEdit, self.PoAButtonEdit,
                     self.AoFButtonEdit, self.PoGButtonEdit]
      
      self.show()
   
   def update_value(self, button, calc):
      interest = float(simple_eval(str(self.interestEdit.text())))
      period = float(simple_eval(str(self.periodEdit.text())))
      
      self.factor = calculations.Factors(interest, period)
      calc = calc(self.factor)
      value = float(simple_eval(str(self.multiplierEdit.text()))) * calc
      
      button.setText(str(calc))
      self.finalValueEdit.setText(str(value))
      
      if is_number(str(self.sumEdit.text())):
         self.sum = float(self.sumEdit.text()) + value
      else:
         self.sum = value
      self.sumEdit.setText(str(self.sum))
      
   def show_FoP(self):
      self.update_value(self.FoPButtonEdit, calculations.FoP)
   
   def show_PoF(self):
      self.update_value(self.PoFButtonEdit, calculations.PoF)
   
   def show_AoP(self):
      self.update_value(self.AoPButtonEdit, calculations.AoP)
      
   def show_PoA(self):
      self.update_value(self.PoAButtonEdit, calculations.PoA)
   
   def show_FoA(self):
      self.update_value(self.FoAButtonEdit, calculations.FoA)
      
   def show_AoF(self):
      self.update_value(self.AoFButtonEdit, calculations.AoF)
   
   def show_AoG(self):
      self.update_value(self.AoGButtonEdit, calculations.AoG)
   
   def show_PoG(self):
      self.update_value(self.PoGButtonEdit, calculations.PoG)
   
   def clear_sum(self):
      self.sumEdit.setText("")
      
   def clear_values(self):
      for self.field in self.fields:
         self.field.setText("")
class ComponentSearchForm():

    data_source = None
    
    related_mashups = None
    
    widget = None
    
    table = None
    
    add_btn = None
    
    graph_form = None
    
    highlighted_api = None
    
    highlighted_mashup = None
    
    def show_main_window(self):
        self.graph_form = matplotlibWidget()
        if self.widget:
            self.widget.destroy()
            self.widget = None;
        self.widget = QWidget()
        self.widget.setMinimumSize(800, 600)
        btn_api = QtGui.QPushButton("Recommend Modules", self.widget)
        btn_api.move(30, 20)

        btn_mashup = QtGui.QPushButton("Recommend Workflows", self.widget)
        btn_mashup.move(200, 20)

        self.textboxLabel = QLabel(self.widget)
        self.textboxLabel.setText("Describe your goals:")
        self.textboxLabel.move(35, 60)
        self.textboxLabel.show
        
        self.textbox = QTextEdit(self.widget)
        self.textbox.move(30, 80)
        self.textbox.setFixedWidth(300)
        self.textbox.setFixedHeight(28)

        btn_api.clicked.connect(self.api_button_clicked)
        btn_mashup.clicked.connect(self.mashups_button_clicked)

        self.table = QTableView(self.widget)
        self.table.clicked.connect(self.table_clicked)
        self.table.setMinimumSize(740, 500)
        self.table.resizeColumnsToContents()
        self.table.move(30, 120)

        self.widget.show()
        
        self.add_btn = QPushButton(self.widget)
        self.add_btn.clicked.connect(self.add_new_api)
        self.add_btn.setText("Add to Palette")
        self.add_btn.hide()
        self.add_btn.move(650, 20)
        
        self.recommendLabel = QLabel(self.widget)
        self.recommendLabel.setText("Also Used")
        self.recommendLabel.move(30, 95)
        self.recommendLabel.hide()
        
        self.switch_btn_apis = QPushButton(self.widget)
        self.switch_btn_apis.clicked.connect(self._show_related_apis)
        self.switch_btn_apis.setText("Related Mashup")
        self.switch_btn_apis.move(500, 20)
        self.switch_btn_apis.hide()
        
        self.switch_btn_mashups = QPushButton(self.widget)
        self.switch_btn_mashups.clicked.connect(self._show_related_mashups)
        self.switch_btn_mashups.setText("Related API")
        self.switch_btn_mashups.move(500, 20)
        self.switch_btn_mashups.hide()

    def __init__(self, parent=None):
        self.data_source = DataSource()
        
    def table_clicked(self):
        """
        Click the table, the graph form may change according to the selection.
        """
        model = self.table.selectionModel()
        indexes = model.selectedIndexes()
        for index in indexes:
            row = index.row()
            data = index.model().headerData(0,Qt.Horizontal).toString()
            newIndex = index.model().index(row, 0)
            if data == "API":
                api_id = get_api_full_name(newIndex.model().data(newIndex).toString())
                api = self.data_source.api_by_id(api_id)
                print api
                mashups = self.data_source.mashups_by_api(api)
                apis = []
                for mashup in mashups:
                    apis.extend(self.data_source.apis_by_mashup(mashup))
                self.graph_form.draw_apis(apis, api, self.highlighted_api)
            else:
                mashup_id = get_mashup_full_name(newIndex.model().data(newIndex).toString())
                mashup = self.data_source.mashup_by_id(mashup_id)
                if not mashup:
                    return
                apis = self.data_source.apis_by_mashup(mashup)
                mashups = []
                if len(apis) > 0:
                    mashups.extend(self.data_source.mashups_by_api(apis[0]))
                self.graph_form.draw_mashups(mashups, mashup, self.highlighted_mashup)
            return


    def _show_apis(self, apis, recommend=False):
        self.switch_btn_apis.hide()
        self.switch_btn_mashups.hide()
        self.recommendLabel.hide()

        row = 0
        model = QStandardItemModel(len(apis), 4)
        model.setColumnCount(4)
        for api in apis:
            model.setData(model.index(row, 0), QVariant(get_api_name(api)))
            model.setData(model.index(row, 1), QVariant(api['protocols']))
            model.setData(model.index(row, 2), QVariant(api['provider']))
            model.setData(model.index(row, 3), QVariant(api['version']))
            row += 1

        model.setHeaderData(0, Qt.Horizontal, QVariant("Module"))
        model.setHeaderData(1, Qt.Horizontal, QVariant("Protocol"))
        model.setHeaderData(2, Qt.Horizontal, QVariant("Provider"))
        model.setHeaderData(3, Qt.Horizontal, QVariant("Version"))

#        model.setHeaderData(0, Qt.Horizontal, QVariant("API"))
#        model.setHeaderData(1, Qt.Horizontal, QVariant("Protocols"))
#        model.setHeaderData(2, Qt.Horizontal, QVariant("Provider"))
#        model.setHeaderData(3, Qt.Horizontal, QVariant("Version"))

        self.table.setModel(model)
        self.table.resizeColumnsToContents()
        
        if recommend:
            self.recommendLabel.show()
        
        self.add_btn.show()

    def _show_mashups(self, mashups):
        self.switch_btn_apis.hide()
        self.switch_btn_mashups.hide()
        self.recommendLabel.hide()

        row = 0
        model = QStandardItemModel(len(mashups), 4)
        model.setColumnCount(4)
        for mashup in mashups:
            model.setData(model.index(row, 0), QVariant(get_mashup_name(mashup)))
            model.setData(model.index(row, 1), QVariant(mashup['title']))
            model.setData(model.index(row, 2), QVariant(mashup['self']))
            model.setData(model.index(row, 3), QVariant(mashup['description']))
            
            row += 1
        
        model.setHeaderData(0, Qt.Horizontal, QVariant("Workflow"))
        model.setHeaderData(1, Qt.Horizontal, QVariant("Short Description"))
        model.setHeaderData(2, Qt.Horizontal, QVariant("Provider"))
        model.setHeaderData(3, Qt.Horizontal, QVariant("Detailed Info"))

#        model.setHeaderData(0, Qt.Horizontal, QVariant("Info"))
#        model.setHeaderData(1, Qt.Horizontal, QVariant("Title"))
#        model.setHeaderData(2, Qt.Horizontal, QVariant("self"))
#        model.setHeaderData(3, Qt.Horizontal, QVariant("Description"))

        self.table.setModel(model)
        self.table.resizeColumnsToContents()
        self.add_btn.show()

    def api_button_clicked(self):
        """
        Trigger to search APIs
        """        
        self.graph_form.draw_api()
        self.graph_form.show()

        apis = self.data_source.apis()
        key = str(self.textbox.toPlainText())
        #Has key or not has key, it is different.
        if key:
            self.api_search_button_clicked()
        else:
            self._show_apis(apis)

    def mashups_button_clicked(self):
        """
        Trigger to search mashups
        """
        self.graph_form.draw_mashup()
        self.graph_form.show()

        key = str(self.textbox.toPlainText())
        if key:
            self.mashup_search_button_clicked()
        else:
            self._show_mashups(self.data_source.mashups())

    #Should probably refactor this into one method.
    def api_search_button_clicked(self):
        """
        Search when no keyword
        """
        self.highlighted_api = None
        self.highlighted_mashup = None
        key = str(self.textbox.toPlainText())
        if key != "":
            apis = self.data_source.search_api(key)
            self._show_apis(apis)

    def mashup_search_button_clicked(self):
        """
        Search when no keyword
        """
        self.highlighted_api = None
        self.highlighted_mashup = None
        key = str(self.textbox.toPlainText())
        if key != "":
            mashups = self.data_source.search_mashup(key)
            self._show_mashups(mashups)
    
    def add_new_api(self):
        """
        Add new api to the modules package.
        """
        apis = self.data_source.apis()
        model = self.table.selectionModel()
        indexes = model.selectedIndexes()
        for index in indexes:
            api = apis[index.row()]
            self._add_new_api(api)
            return
    
    def add_related_api(self):
        objs = []
        for mashup in self.related_mashups:
            objs.append(mashup)
            for api in mashup["related_mashups"]:
                objs.append(api)
        model = self.table.selectionModel()
        indexes = model.selectedIndexes()
        for index in indexes:
            api = objs[index.row()]
            if api.get("protocols"):
                self._add_new_api(api)
                return

    def _show_related_mashups(self):
        self.switch_btn_apis.hide()
        self.switch_btn_mashups.hide()
        self.recommendLabel.hide()
        
        apis = []
        objs = []
        for mashup in self.related_mashups:
            apis.extend(mashup["related_mashups"])

        for api in apis:
            objs.append(api)
            mashups = self.data_source.mashups_by_api(api)
            objs.extend(mashups)

        row = 0
        model = QStandardItemModel(len(objs), 4)
        model.setColumnCount(4)
        for obj in objs:
            if obj.get('protocols'):
                model.setData(model.index(row, 0), QVariant(get_api_name(obj)))
                model.setData(model.index(row, 1), QVariant(obj['protocols']))
                model.setData(model.index(row, 2), QVariant(obj['provider']))
            else:
                model.setData(model.index(row, 3), QVariant(get_mashup_name(obj)))
            row += 1

        model.setHeaderData(0, Qt.Horizontal, QVariant("API"))
        model.setHeaderData(1, Qt.Horizontal, QVariant("Protocols"))
        model.setHeaderData(2, Qt.Horizontal, QVariant("Provider"))
        model.setHeaderData(3, Qt.Horizontal, QVariant("Mashup"))
        self.table.setModel(model)
        self.table.resizeColumnsToContents()
        self.switch_btn_apis.show()

    def _show_related_apis(self):
        self.switch_btn_apis.hide()
        self.switch_btn_mashups.hide()
        self.recommendLabel.hide()
        
        row = 0
        objs = []
        for mashup in self.related_mashups:
            objs.append(mashup)
            for api in mashup["related_mashups"]:
                objs.append(api)
        #Combining similarity and related.
        similar_apis = self.data_source.search_api_similarity(self.highlighted_api)
        #return str(mashup['id'])[(len("http://www.programmableweb.com/mashup/")):]
        objs.append({'id': "http://www.programmableweb.com/mashup/Using-Similarity-Metric"})
        objs.extend(similar_apis)
        #Combining similarity and related.

        model = QStandardItemModel(len(objs), 5)
        for obj in objs:
            if obj.get('protocols'):
                model.setData(model.index(row, 1), QVariant(get_api_name(obj)))
                model.setData(model.index(row, 2), QVariant(obj['protocols']))
                model.setData(model.index(row, 3), QVariant(obj['provider']))
                model.setData(model.index(row, 4), QVariant(obj['version']))
            else:
                model.setData(model.index(row, 0), QVariant(get_mashup_name(obj)))
            row += 1

        model.setHeaderData(0, Qt.Horizontal, QVariant("Mashup"))
        model.setHeaderData(1, Qt.Horizontal, QVariant("API"))
        model.setHeaderData(2, Qt.Horizontal, QVariant("Protocols"))
        model.setHeaderData(3, Qt.Horizontal, QVariant("Provider"))
        model.setHeaderData(4, Qt.Horizontal, QVariant("Version"))

        self.table.setModel(model)
        self.switch_btn_mashups.show()

    def _add_new_api(self, api):
        self.highlighted_api = api
        mashups = self.data_source.mashups_by_api(api)
        for mashup in mashups:
            mashup['related_mashups'] = (self.data_source.apis_by_mashup(mashup))
        if len(mashups) > 0:
            self.related_mashups = mashups
            self._show_related_apis()
        manager = core.packagemanager.get_package_manager()
        reg = core.modules.module_registry.get_module_registry()
        package = manager.get_package("edu.cmu.sv.components", "1.0.0")
        core.modules.module_registry.set_current_package(package)

        if (api["protocols"] == "SOAP" and api["wsdl"] != ""):
            s = Service(api["wsdl"])
            add_new_service(s, api["wsdl"])
        else:
            new_module = vistrails_module.new_module(Module, get_api_name(api))
            reg.add_module(new_module)
    
            reg.add_input_port(new_module, "value1",
                         (core.modules.basic_modules.String, 'the first argument'))
            reg.add_input_port(new_module, "value2",
                         (core.modules.basic_modules.String, 'the second argument'))
            reg.add_output_port(new_module, "value",
                          (core.modules.basic_modules.String, 'the result'))
class YPipeWidget(QWidget):
	
	def __init__(self, leftFlow = 0, rightFlow = 0, maxFlow = 100, parent = None):
		super(YPipeWidget, self).__init__(parent)

		self.leftSpinBox = QSpinBox(self)
		self.leftSpinBox.setRange(0, maxFlow)
		self.leftSpinBox.setValue(leftFlow)
		self.leftSpinBox.setSuffix(" l/s")
		self.leftSpinBox.setAlignment(Qt.AlignRight|Qt.AlignVCenter)
		self.connect(self.leftSpinBox, SIGNAL("valueChanged(int)"), self.valueChanged)

		self.rightSpinBox = QSpinBox(self)
		self.rightSpinBox.setRange(0, maxFlow)
		self.rightSpinBox.setValue(rightFlow)
		self.rightSpinBox.setSuffix(" l/s")
		self.rightSpinBox.setAlignment(Qt.AlignRight|Qt.AlignVCenter)
		self.connect(self.rightSpinBox, SIGNAL("valueChanged(int)"), self.valueChanged)

		self.label = QLabel(self)
		self.label.setFrameStyle(QFrame.StyledPanel | QFrame.Sunken)
		self.label.setAlignment(Qt.AlignCenter)
		fm = QFontMetricsF(self.font())
		self.label.setMinimumWidth(fm.width(" 999 l/s "))

		self.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))

		self.setMinimumSize(self.minimumSizeHint())
		self.valueChanged()

	def valueChanged(self):
		a = self.leftSpinBox.value()
		b = self.rightSpinBox.value()
		self.label.setText("{0}".format(a + b))
		self.emit(SIGNAL("valueChanged"), a, b)
		self.update()

	def values(self):
		return self.leftSpinBox.value(), self.rightSpinBox.value()

	def minimumSizeHint(self):
		return QSize(self.leftSpinBox.width() * 3, self.leftSpinBox.height())

	def resizeEvent(self, event = None):
		fm = QFontMetricsF(self.font())
		x = (self.width() - self.label.width()) / 2
		y = self.height() - (fm.height() * 1.5)
		self.label.move(x, y)

		y = self.height() / 60.0
		x = (self.width() / 4.0) - self.leftSpinBox.width()
		self.leftSpinBox.move(x, y)

		x = self.width() - (self.width() / 4.0)
		self.rightSpinBox.move(x, y)

	def paintEvent(self, event = None):
		
		LogicalSize = 100.0

		def logicalFromPhysical(length, side):
			return (length / side) * LogicalSize

		fm = QFontMetricsF(self.font())
		ymargin = ((LogicalSize / 30.0) + logicalFromPhysical(self.leftSpinBox.height(), self.height()))
		ymax = (LogicalSize - logicalFromPhysical(fm.height() * 2, self.height()))
		width = LogicalSize / 4.0
		
		cx, cy = LogicalSize / 2.0, LogicalSize / 3.0
		ax, ay = cx - (2 * width), ymargin
		bx, by = cx - width, ay
		dx, dy = cx + width, ay
		ex, ey = cx + (2 * width), ymargin
		fx, fy = cx + (width / 2), cx + (LogicalSize / 24.0)
		gx, gy = fx, ymax
		hx, hy = cx - (width / 2), ymax
		ix, iy = hx, fy

		painter = QPainter(self)
		painter.setRenderHint(QPainter.Antialiasing)
		side = min(self.width(), self.height())
		painter.setViewport((self.width() - side) / 2, (self.height() - side) / 2, side, side)
		painter.setWindow(0, 0, LogicalSize, LogicalSize)

		painter.setPen(Qt.NoPen)

		gradient = QLinearGradient(QPointF(0, 0), QPointF(0, 100))
		gradient.setColorAt(0, Qt.white)
		a = self.leftSpinBox.value()
		gradient.setColorAt(1, (Qt.red if a != 0 else Qt.white))
		painter.setBrush(QBrush(gradient))
		painter.drawPolygon(QPolygon([ax, ay, bx, by, cx, cy, ix, iy]))

		gradient = QLinearGradient(QPointF(0, 0), QPointF(0, 100))
		gradient.setColorAt(0, Qt.white)
		b = self.rightSpinBox.value()
		gradient.setColorAt(1, (Qt.blue if b != 0 else Qt.white))
		painter.setBrush(QBrush(gradient))
		painter.drawPolygon(QPolygon([cx, cy, dx, dy, ex, ey, fx, fy]))

		if (a + b) == 0:
			color = QColor(Qt.white)
		else:
			ashare = (a / (a + b)) * 255.0
			bshare = 255.0 - ashare
			color = QColor(ashare, 0, bshare)

		gradient = QLinearGradient(QPointF(0, 0), QPointF(0, 100))
		gradient.setColorAt(0, Qt.white)
		gradient.setColorAt(1, color)
		painter.setBrush(QBrush(gradient))
		painter.drawPolygon(QPolygon([cx, cy, fx, fy, gx, gy, hx, hy, ix, iy]))

		painter.setPen(Qt.black)
		painter.drawPolyline(QPolygon([ax, ay, ix, iy, hx, hy]))
		painter.drawPolyline(QPolygon([gx, gy, fx, fy, ex, ey]))
		painter.drawPolyline(QPolygon([bx, by, cx, cy, dx, dy]))
Exemplo n.º 33
0
class urlgroup(QGroupBox):
    def __init__(self, parent=None):
        super(urlgroup, self).__init__(parent)
        self.setGeometry(10,30,500,80)
        self.setObjectName('urlgroup')
        self.urlbar = QLineEdit()
        self.urlbar.setObjectName('urlbar')
        self.urlbar.setText('Collez votre URL içi')
        self.urlbar.setStyleSheet('font-weight:lighter;color:gray;')
        self.urlbar.show()
        self.parsebutton = QPushButton('Go !!')
        self.parsebutton.setObjectName('parsebutton')
        self.parsebutton.show()
        layout = QBoxLayout(QBoxLayout.LeftToRight, self)
        layout.addWidget(self.urlbar)
        layout.addWidget(self.parsebutton)
        self.show()
        self.group2 = QGroupBox(parent)
        self.group2.setObjectName('core')
        self.group2.setGeometry(10,120,500,280)
        self.group2.show()
        self.group3 = QGroupBox(self.group2)
        self.group3.setObjectName('albuminfos')
        self.group3.setGeometry(10,15,200,245)
        self.group3.show()
        self.itemlist = QListWidget(self.group2)
        self.itemlist.setGeometry(250,15,230,245)
        self.itemlist.show()
        self.dlgroup = QGroupBox(parent)
        self.dlgroup.setObjectName('dlgroup')
        self.dlgroup.setGeometry(10,420,500,100)
        self.dlgroup.show()
        self.dlgroup.dlbutton = QPushButton('Download', self.dlgroup)
        self.dlgroup.dlbutton.setObjectName('dlbutton')
        self.dlgroup.dlbutton.move(10,20)
        self.dlgroup.dlbutton.show()
        self.dlgroup.progressbar = QProgressBar(self.dlgroup)
        self.dlgroup.progressbar.setObjectName('progressbar')
        self.dlgroup.progressbar.setGeometry(100,21,380,21)
        self.dlgroup.progressbar.show()
        self.dlgroup.dlinfos = QLabel(self.dlgroup)
        self.dlgroup.dlinfos.setGeometry(100,70,200,21)
        self.dlgroup.dlinfos.show()
        self.dlgroup.dledfile = QLabel(self.dlgroup)
        self.dlgroup.dledfile.setGeometry(300,70,200,21)
        self.dlgroup.dledfile.show()
        self.dlgroup.dlto = QLineEdit('C:\\', self.dlgroup)
        self.dlgroup.dlto.setGeometry(100,50,350,21)
        self.dlgroup.dlto.show()
        self.dlgroup.dlto.changebt = QToolButton(self.dlgroup)
        self.dlgroup.dlto.changebt.setObjectName('dltobt')
        self.dlgroup.dlto.changebt.setGeometry(10,50,75,21)
        self.dlgroup.dlto.changebt.setText('To')
        self.dlgroup.dlto.changebt.show()
        self.dlgroup.dlto.openf = QPushButton('Open', self.dlgroup)
        self.dlgroup.dlto.openf.setGeometry(455,50,35,21)
        self.dlgroup.dlto.openf.setObjectName('openfolder')
        self.dlgroup.dlto.openf.show()  
        self.album = QLabel(self.group3)
        self.artist = QLabel(self.group3)
        self.year = QLabel(self.group3)
        self.tracks = QLabel(self.group3)
        self.coverart = QLabel(self.group3)
        self.urlbar.setFocus(True)
        self.connect(self.parsebutton, SIGNAL('clicked()'), self.parseclicked )
        self.connect(self.dlgroup.dlbutton, SIGNAL('clicked()'), self.launchdl)
        self.connect(self.dlgroup.dlto.changebt, SIGNAL('clicked()'), self.changedir)
        self.connect(self.dlgroup.dlto.openf, SIGNAL('clicked()'), self.openfolder)
        
    def parseclicked(self):
        self.itemlist.clear()
        url = str(self.urlbar.text())
        self.infos = getsonglist(url)
        if (self.infos == 'connexion impossible') or (self.infos == 'unsupported'):
            self.error = QMessageBox()
            if self.infos == 'connexion impossible':
                self.error.setText('Connexion Impossible !')
            elif self.infos == 'unsupported':
                self.error.setText('Site Unsupported !!')
            self.error.setWindowTitle('Erreur!')
            self.error.setIcon(QMessageBox.Warning)
            self.icon = QIcon('images/mainwindowicon.png')
            self.error.setWindowIcon(self.icon)
            self.error.exec_()
        else:
            self.artist.setText('Artiste : ' + self.infos['artist'])
            self.artist.move(40,175)
            self.artist.show()
            self.album.setText('Album : ' + self.infos['albumname'])
            self.album.move(40,190)
            self.album.show()
            try:
                self.year.setText('Annee : ' + self.infos['year'])
                
            except KeyError:
                self.year.setText('Annee : ' + 'N/A')
            self.year.move(40,205)
            self.year.show()
            self.tracks.setText('Tracks : ' + str(self.infos['tracks']))
            self.tracks.move(40,220)
            self.tracks.show()
            coverartpix = QPixmap(self.infos['coverart'])
            coverartpix = coverartpix.scaled(178,135,)
            self.coverart.setPixmap(coverartpix) 
            self.coverart.move(10,10)
            self.coverart.show()
            self.list2 = []
            for item in self.infos['titles']:
                item = tracklistitems(item)
                self.list2.append(item)
            for item in self.list2:
                self.itemlist.addItem(item)
                
            
            
            

    def launchdl(self):
        if self.dlgroup.dlbutton.text() == 'Download':
            try:
                self.itemlist.item(self.currentitem).setText(self.text)
            except:
                pass
            self.dlgroup.dlbutton.setText('Stop')
            rmtree('tmpimg', True)
            i= 0
            dllist = []
            for item in self.list2:
                if item.eligible() =='Checked':
                    dllist.append(i)
                i= i+1
            self.stritemlist = []
            for i in range(0,self.infos['tracks']):
                #print i
                #print self.itemlist.item(i).text()
                #TODO: hamida album breaks, recheck regexes
                self.stritemlist.append(str(self.itemlist.item(i).text()))
            dlto =  self.dlgroup.dlto.text()
            self.thread = dlThread(dllist, self.infos, dlto, self.stritemlist) 
            self.connect(self.thread, SIGNAL('progress(PyQt_PyObject)'), self.updateProgress)
            self.connect(self.thread, SIGNAL('dledfile(PyQt_PyObject)'), self.updateDlednow)
            self.thread.start()
        else:
            self.dlgroup.dlbutton.setText('Download')
            self.thread.terminate()
      
    def updateProgress(self, progress):
        self.dlgroup.progressbar.setValue(progress['bar'])
        self.dlgroup.dlinfos.setText(progress['info'])
        self.text = self.stritemlist[progress['item']]
        self.currentitem = progress['item']
        self.percent = str(progress['bar']) + ' % - '
        self.percent = QString(self.percent)
        self.dlingicon = QIcon('images/dling.png')
        self.doneicon = QIcon('images/done.png')
        self.itemlist.item(progress['item']).setIcon(self.dlingicon)
        self.itemlist.item(progress['item']).setText(self.percent + self.text)
        if progress['bar'] >= 98:
            self.itemlist.item(progress['item']).setIcon(self.doneicon)
            self.itemlist.item(progress['item']).setText(self.text)
            self.itemlist.item(progress['item']).setCheckState(Qt.Unchecked)
            self.itemlist.item(progress['item']).setFlags(Qt.ItemIsEnabled | Qt.ItemIsEditable | Qt.ItemIsSelectable)
            
    def updateDlednow(self, dledfile):
        self.dlgroup.dledfile.setText(dledfile)

    
    def changedir(self):
        self.dir = QFileDialog.getExistingDirectory()
        self.dlgroup.dlto.setText(self.dir + '/')
    def openfolder(self):
        startfile(self.dlgroup.dlto.text())
        
    def stopdl(self):
        pass
Exemplo n.º 34
0
    def home(self):
        self.imgindex = 0
        self.selectedname = ""
        self.imglen = 0
        self.delbtn = QtGui.QPushButton("Delete Entry", self)
        self.delbtn.resize(100, 30)
        self.delbtn.move(200, 125)
        # self.delbtn.move(0, 0)

        self.rightname = QLabel("", self)
        self.rightname.move(350, 5)
        self.rightname.resize(600, 20)
        self.rightname.setAlignment(Qt.AlignCenter)

        self.btn = QtGui.QPushButton("Enroll", self)
        # self.btn.clicked.connect()
        self.btn.resize(80, 30)
        self.btn.move(10, 125)

        self.nextbtn = QtGui.QPushButton("Next", self)
        self.delimagebtn = QtGui.QPushButton("Delete Image", self)
        self.previousbtn = QtGui.QPushButton("Previous", self)
        self.nextbtn.move(750, 530)
        self.delimagebtn.move(550, 530)
        self.previousbtn.move(450, 530)

        self.firstnametext = QLabel(self)
        self.firstnametext.setText("First Name:")
        self.firstnametext.move(10, 10)

        self.firstnamefield = QLineEdit(self)
        self.firstnamefield.setObjectName("First Name")
        self.firstnamefield.resize(300, 30)
        self.firstnamefield.move(100, 10)

        lastnametext = QLabel(self)
        lastnametext.setText("Last Name:")
        lastnametext.move(10, 50)

        self.lastnamefield = QLineEdit(self)
        self.lastnamefield.setObjectName("First Name")
        self.lastnamefield.resize(300, 30)
        self.lastnamefield.move(100, 50)

        self.dirbtn = QtGui.QPushButton("Choose Directory", self)
        self.dirbtn.resize(140, 30)
        self.dirbtn.move(10, 90)

        self.dirfield = QLineEdit(self)
        self.dirfield.setObjectName("Directory")
        self.dirfield.resize(250, 30)
        self.dirfield.move(150, 90)

        self.status = QLabel(self)
        self.status.move(10, 563)
        self.status.resize(400, 20)
        self.status.setText("Ready")

        self.rebuild = QtGui.QPushButton("Add Image", self)
        self.rebuild.move(650, 530)
        self.rebuild.resize(100, 30)

        self.listsize = QtGui.QLabel(self)
        self.listsize.setText(" Persons Enrolled")
        self.listsize.resize(200, 20)
        self.listsize.move(10, 160)

        self.list = QListWidget(self)
        self.list.resize(389, 380)
        self.list.move(10, 180)
        self.stat("Pulling list")
        refresh_list_elements(self.list, self.listsize)
        self.stat("Ready")

        self.image = QLabel(self)
        self.image.resize(490, 490)
        self.image.move(405, 30)

        self.list.doubleClicked.connect(self.on_double_click)
        self.connect(self, SIGNAL('triggered()'), self.closeEvent)
        self.connect(self.rebuild, SIGNAL("clicked()"), self.add_image)
        self.connect(self.nextbtn, SIGNAL("clicked()"), self.next_image)
        self.connect(self.previousbtn, SIGNAL("clicked()"),
                     self.previous_image)
        self.connect(self.delimagebtn, SIGNAL("clicked()"), self.delete_image)
        self.connect(self.dirbtn, SIGNAL("clicked()"), self.opendir)
        self.connect(self.delbtn, SIGNAL("clicked()"), self.button_delete)
        self.connect(self.btn, SIGNAL("clicked()"), self.button_click)
        self.show()
Exemplo n.º 35
0
class Window(QtGui.QMainWindow):
    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(50, 50, 900, 590)
        self.setWindowTitle("CUBS FaceDemo Enroller")
        self.home()

    def home(self):
        self.imgindex = 0
        self.selectedname = ""
        self.imglen = 0
        self.delbtn = QtGui.QPushButton("Delete Entry", self)
        self.delbtn.resize(100, 30)
        self.delbtn.move(200, 125)
        # self.delbtn.move(0, 0)

        self.rightname = QLabel("", self)
        self.rightname.move(350, 5)
        self.rightname.resize(600, 20)
        self.rightname.setAlignment(Qt.AlignCenter)

        self.btn = QtGui.QPushButton("Enroll", self)
        # self.btn.clicked.connect()
        self.btn.resize(80, 30)
        self.btn.move(10, 125)

        self.nextbtn = QtGui.QPushButton("Next", self)
        self.delimagebtn = QtGui.QPushButton("Delete Image", self)
        self.previousbtn = QtGui.QPushButton("Previous", self)
        self.nextbtn.move(750, 530)
        self.delimagebtn.move(550, 530)
        self.previousbtn.move(450, 530)

        self.firstnametext = QLabel(self)
        self.firstnametext.setText("First Name:")
        self.firstnametext.move(10, 10)

        self.firstnamefield = QLineEdit(self)
        self.firstnamefield.setObjectName("First Name")
        self.firstnamefield.resize(300, 30)
        self.firstnamefield.move(100, 10)

        lastnametext = QLabel(self)
        lastnametext.setText("Last Name:")
        lastnametext.move(10, 50)

        self.lastnamefield = QLineEdit(self)
        self.lastnamefield.setObjectName("First Name")
        self.lastnamefield.resize(300, 30)
        self.lastnamefield.move(100, 50)

        self.dirbtn = QtGui.QPushButton("Choose Directory", self)
        self.dirbtn.resize(140, 30)
        self.dirbtn.move(10, 90)

        self.dirfield = QLineEdit(self)
        self.dirfield.setObjectName("Directory")
        self.dirfield.resize(250, 30)
        self.dirfield.move(150, 90)

        self.status = QLabel(self)
        self.status.move(10, 563)
        self.status.resize(400, 20)
        self.status.setText("Ready")

        self.rebuild = QtGui.QPushButton("Add Image", self)
        self.rebuild.move(650, 530)
        self.rebuild.resize(100, 30)

        self.listsize = QtGui.QLabel(self)
        self.listsize.setText(" Persons Enrolled")
        self.listsize.resize(200, 20)
        self.listsize.move(10, 160)

        self.list = QListWidget(self)
        self.list.resize(389, 380)
        self.list.move(10, 180)
        self.stat("Pulling list")
        refresh_list_elements(self.list, self.listsize)
        self.stat("Ready")

        self.image = QLabel(self)
        self.image.resize(490, 490)
        self.image.move(405, 30)

        self.list.doubleClicked.connect(self.on_double_click)
        self.connect(self, SIGNAL('triggered()'), self.closeEvent)
        self.connect(self.rebuild, SIGNAL("clicked()"), self.add_image)
        self.connect(self.nextbtn, SIGNAL("clicked()"), self.next_image)
        self.connect(self.previousbtn, SIGNAL("clicked()"),
                     self.previous_image)
        self.connect(self.delimagebtn, SIGNAL("clicked()"), self.delete_image)
        self.connect(self.dirbtn, SIGNAL("clicked()"), self.opendir)
        self.connect(self.delbtn, SIGNAL("clicked()"), self.button_delete)
        self.connect(self.btn, SIGNAL("clicked()"), self.button_click)
        self.show()

    def closeEvent(self, event):
        self.stat("Saving Changes")
        save()
        print "Changes saved"
        print "Rebuilding Vectors"
        self.rebuild_vector()
        self.destroy()

    def rebuild_vector(self):
        # feature_build.generate_vectors()
        pass

    def stat(self, stat):
        self.status.setText(stat)

    def add_image(self):
        self.dialog = QFileDialog(self)
        directory = self.dialog.getOpenFileName(self, 'Select Directory')
        if directory:
            self.dirfield.setText(directory)
        img_directory = str(self.dirfield.text())
        picarray = test_create_image(img_directory, True)
        # enroll_images.images_to_array(img_directory, True)
        dict_personinfo[self.selectedname].append(picarray)
        refresh_list_elements(self.list, self.listsize)
        self.init_images()
        self.dirfield.setText('')

    def next_image(self):
        check = self.imgindex + 1
        if (check >= self.imglen):
            self.display_image(0)
            self.imgindex = 0
        else:
            self.display_image(check)
            self.imgindex += 1

    def previous_image(self):
        check = self.imgindex - 1
        if (check < 0):
            self.display_image(self.imglen - 1)
            self.imgindex = self.imglen - 1
        else:
            self.display_image(check)
            self.imgindex -= 1

    def delete_image(self):
        # dict_personinfo = obtain_info()
        dict_personinfo[self.selectedname].pop(self.imgindex)
        if (len(dict_personinfo[self.selectedname]) == 0):
            dict_personinfo.pop(self.selectedname, None)
            # with open('data/gui_dict.pickle', 'wb') as handle:
            #     cPickle.dump(dict_personinfo, handle)
            self.stat("Deleted " + self.selectedname)
            refresh_list_elements(self.list, self.listsize)
            self.image.clear()
            self.rightname.setText("")
        else:
            # with open('data/gui_dict.pickle', 'wb') as handle:
            #     cPickle.dump(dict_personinfo, handle)
            self.stat("Deleted image for " + self.selectedname)
            refresh_list_elements(self.list, self.listsize)
            self.init_images()

    def display_image(self, index=0):
        img = self.get_images()
        self.imglen = len(img)
        img = img[index]
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        height, width, channel = img.shape
        bytesPerLine = 3 * width
        qimg = QImage(img.data, width, height, bytesPerLine,
                      QImage.Format_RGB888)
        pixmap = QtGui.QPixmap(qimg)
        pixmap = pixmap.scaled(self.image.size())
        self.image.setPixmap(pixmap)

    def get_images(self):
        # dict_personinfo = obtain_info()
        arr_images = []
        for i in range(len(dict_personinfo[self.selectedname])):
            frame = dict_personinfo[self.selectedname][i][0]
            rectangle = dict_personinfo[self.selectedname][i][1]
            img = np.array(Image.fromarray(frame))
            cv2.rectangle(img, (int(rectangle[0][0]), int(rectangle[0][3])),
                          (int(rectangle[0][2]), int(rectangle[0][1])),
                          (0, 255, 0), 40)
            cv2.circle(img, (int(rectangle[0][5]), int(rectangle[0][6])), 10,
                       (0, 255, 0), 40)
            cv2.circle(img, (int(rectangle[0][7]), int(rectangle[0][8])), 10,
                       (0, 255, 0), 40)
            cv2.circle(img, (int(rectangle[0][9]), int(rectangle[0][10])), 10,
                       (0, 255, 0), 40)
            cv2.circle(img, (int(rectangle[0][11]), int(rectangle[0][12])), 10,
                       (0, 255, 0), 40)
            cv2.circle(img, (int(rectangle[0][13]), int(rectangle[0][14])), 10,
                       (0, 255, 0), 40)

            print(rectangle)
            arr_images.append(img)
        self.imglen = len(arr_images)
        return arr_images

    def on_double_click(self):
        self.selectedname = str(self.list.currentItem().text())
        self.rightname.setText(self.selectedname)
        self.init_images()

    def init_images(self):
        self.imgindex = 0
        img = self.get_images()
        img = img[0]
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        height, width, channel = img.shape
        bytesPerLine = 3 * width
        qimg = QImage(img.data, width, height, bytesPerLine,
                      QImage.Format_RGB888)
        pixmap = QtGui.QPixmap(qimg)
        pixmap = pixmap.scaled(self.image.size())
        self.image.setPixmap(pixmap)

    def opendir(self):
        self.dialog = QFileDialog(self)
        directory = self.dialog.getExistingDirectory(self, 'Select Directory')
        if directory:
            self.dirfield.setText(directory)

    def button_delete(self):
        if (str(self.list.currentItem().text()) != None):
            # dict_personinfo = obtain_info()
            dict_personinfo.pop(str(self.list.currentItem().text()), None)
            # with open('data/gui_dict.pickle', 'wb') as handle:
            #     cPickle.dump(dict_personinfo, handle)
            self.stat("Deleted " + str(self.list.currentItem().text()))
            refresh_list_elements(self.list, self.listsize)
            self.image.clear()
            self.rightname.clear()
        else:
            pass

    def button_click(self):
        self.stat("Pulling list")
        # dict_personinfo = obtain_info()
        self.stat("Ready")

        name = ['', '']
        name[0] = str(self.firstnamefield.text())
        name[1] = str(self.lastnamefield.text())
        name[0] = name[0].replace(" ", "")
        name[1] = name[1].replace(" ", "")
        img_directory = str(self.dirfield.text())

        self.stat("Detecting Face")
        if img_directory == "" or len(name[0]) == 0:
            picarray = []
        else:
            picarray = test_create_image(
                img_directory, False)  # Just a testing filler for now
            # picarray = enroll_images.images_to_array(img_directory, False)

        # feature_build.generate_vectors()

        if len(picarray) != 0:
            dict_personinfo[name[0] + " " + name[1]] = {}
            dict_personinfo[name[0] + " " + name[1]] = picarray

            if img_directory == "" or len(name[0]) == 0:
                self.stat("Failed to add " + name[0] + " " + name[1])
            else:
                self.stat("Writing")
                # with open('data/gui_dict.pickle', 'wb') as handle:
                #     cPickle.dump(dict_personinfo, handle)
                self.stat("Added " + name[0] + " " + name[1] + " with " +
                          str(len(picarray)) + " images")
        else:
            self.stat("Failed to add " + name[0] + " " + name[1])
        # feature_build.generate_vectors()
        self.firstnamefield.setText('')
        self.lastnamefield.setText('')
        self.dirfield.setText('')
        # self.list.addItem(name[0] + " " + name[1])
        refresh_list_elements(self.list, self.listsize)
Exemplo n.º 36
0
    def show_main_window(self):
        self.graph_form = matplotlibWidget()
        if self.widget:
            self.widget.destroy()
            self.widget = None;
        self.widget = QWidget()
        self.widget.setMinimumSize(800, 600)

        ds_label = QLabel(self.widget)
        ds_label.setText("Data Source:")
        ds_label.move(30,20)
        self.ds = QtGui.QComboBox(self.widget)
        self.ds.addItem("NASA/MODIS")
        self.ds.addItem("NASA/AMSRE")
        self.ds.move(30, 40)

        var_label = QLabel(self.widget)
        var_label.setText("Variable Name:")
        var_label.move(150,20)
        self.var = QtGui.QComboBox(self.widget)
        self.var.addItem("Precipitation Flux")
        self.var.addItem("Total Cloud Fraction")
        self.var.move(150, 40)
        self.var.setCurrentIndex(1)
        
        self.sdate = QTextEdit("2004-01", self.widget)
        self.sdate.move(30, 100)
        self.sdate.setFixedWidth(100)
        self.sdate.setFixedHeight(30)
#        print self.sdate.toPlainText()

        sdate_label = QLabel(self.widget)
        sdate_label.setText("Start Date")
        sdate_label.move(30, 80)

        self.edate = QTextEdit("2004-12", self.widget)
        self.edate.move(150, 100)
        self.edate.setFixedWidth(100)
        self.edate.setFixedHeight(30)

        edate_label = QLabel(self.widget)
        edate_label.setText("End Date")
        edate_label.move(150, 80)

        self.slat = QTextEdit("-90", self.widget)
        self.slat.move(270, 100)
        self.slat.setFixedWidth(100)
        self.slat.setFixedHeight(30)

        slat_label = QLabel(self.widget)
        slat_label.setText("Start Lat (deg)")
        slat_label.move(270, 80)

        self.elat = QTextEdit("90", self.widget)
        self.elat.move(390, 100)
        self.elat.setFixedWidth(100)
        self.elat.setFixedHeight(30)

        elat_label = QLabel(self.widget)
        elat_label.setText("End Lat (deg)")
        elat_label.move(390, 80)

        self.slon = QTextEdit("0", self.widget)
        self.slon.move(510, 100)
        self.slon.setFixedWidth(100)
        self.slon.setFixedHeight(30)

        slon_label = QLabel(self.widget)
        slon_label.setText("Start Lon (deg)")
        slon_label.move(510, 80)

        self.elon = QTextEdit("360", self.widget)
        self.elon.move(630, 100)
        self.elon.setFixedWidth(100)
        self.elon.setFixedHeight(30)

        elon_label = QLabel(self.widget)
        elon_label.setText("End Lon (deg)")
        elon_label.move(630, 80)

        self.cb1 = QtGui.QCheckBox('January', self.widget)
        self.cb1.move(30,160)
        self.cb1.setChecked(True)
        self.cb2 = QtGui.QCheckBox('February', self.widget)
        self.cb2.move(130,160)
        self.cb2.setChecked(True)
        self.cb3 = QtGui.QCheckBox('March', self.widget)
        self.cb3.move(230,160)
        self.cb3.setChecked(True)
        self.cb4 = QtGui.QCheckBox('April', self.widget)
        self.cb4.move(330,160)
        self.cb4.setChecked(True)
        self.cb5 = QtGui.QCheckBox('May', self.widget)
        self.cb5.move(430,160)
        self.cb5.setChecked(True)
        self.cb6 = QtGui.QCheckBox('June', self.widget)
        self.cb6.move(530,160)
        self.cb6.setChecked(True)
        self.cb7 = QtGui.QCheckBox('July', self.widget)
        self.cb7.move(30,200)
        self.cb7.setChecked(True)
        self.cb8 = QtGui.QCheckBox('August', self.widget)
        self.cb8.move(130,200)
        self.cb8.setChecked(True)
        self.cb9 = QtGui.QCheckBox('September', self.widget)
        self.cb9.move(230,200)
        self.cb9.setChecked(True)
        self.cb10 = QtGui.QCheckBox('October', self.widget)
        self.cb10.move(330,200)
        self.cb10.setChecked(True)
        self.cb11 = QtGui.QCheckBox('November', self.widget)
        self.cb11.move(430,200)
        self.cb11.setChecked(True)
        self.cb12 = QtGui.QCheckBox('December', self.widget)
        self.cb12.move(530,200)
        self.cb12.setChecked(True)

        cscale_label = QLabel(self.widget)
        cscale_label.setText("Color Scale")
        cscale_label.move(30, 240)
        self.rbg = QtGui.QButtonGroup(self.widget)
        self.rb1 = QtGui.QRadioButton('Linear', self.widget)
        self.rb1.move(130,240)

        self.rb2 = QtGui.QRadioButton('Logarithmic', self.widget)
        self.rb2.move(230,240)
        self.rbg.addButton(self.rb1)
        self.rbg.addButton(self.rb2)
        self.rb1.setChecked(True)
#        print self.rb1.isChecked()
        self.btn_call_service = QtGui.QPushButton("Call Service", self.widget)
        self.btn_call_service.move(30,280)
        self.btn_call_service.clicked.connect(self.button_call_service)


        btn_api = QtGui.QPushButton("Recommend Modules", self.widget)
        btn_api.move(30, 20)
        btn_api.hide()

        btn_mashup = QtGui.QPushButton("Recommend Workflows", self.widget)
        btn_mashup.move(200, 20)
        btn_mashup.hide()
        self.widget.show()
Exemplo n.º 37
0
class RecordWidget(QWidget):
    def __init__(self,parent=None):
        super(RecordWidget,self).__init__(parent)
        self.setFixedSize(900,400)
        self.setWindowFlags(Qt.FramelessWindowHint|Qt.WindowStaysOnTopHint)
        self.setStyleSheet("QTextBrowser{border:5px;}"
                           "QTextBrowser{background:black;}"
                           "QTextBrowser{color:white;}"
                           "QTextBrowser{font-size:15px;}")
        
        self.topLine = 50
        self.mythread = MyThread()
        self.mythread.start()
        
        self.textBrowser = QTextBrowser(self)
        self.textBrowser.setFixedSize(self.geometry().width()-20,self.geometry().height()-self.topLine-45)
        self.textBrowser.move(10,self.topLine)
        
        self.pauseButton = QPushButton(self)
        self.pauseButton.setFixedSize(880,30)
        self.pauseButton.setText(self.tr("Pause"))
        self.pauseButton.move(10,self.height()-40)
        self.pauseButton.setStyleSheet("QPushButton{background:rgb(180,200,255);}"
                                       "QPushButton{border:0px;}"
                                       "QPushButton:hover{background:rgb(100,100,100);}"
                                       "QPushButton:pressed{background:rgb(80,0,255);}")
        self.connect(self.pauseButton, SIGNAL("clicked()"),self.pauseThread)
        
        
        self.closeButton = QPushButton(self)
        self.closeButton.setFixedSize(30,30)
        self.closeButton.setIcon(QIcon("images/close.png"))
        self.closeButton.setStyleSheet("QPushButton{border:0px;}"
                                       "QPushButton:hover{background:rgb(180,200,255);}"
                                       "QPushButton:pressed{background:rgb(80,0,255);}")
        self.closeButton.move(self.geometry().width()-35,5)
        
        self.connect(self.closeButton,SIGNAL("clicked()"),self.cancel)
        
        
        #self.mainLayout = QHBoxLayout(self)
        #self.mainLayout.setMargin(0)
        #self.mainLayout.addSpacing(30)
        #self.mainLayout.addWidget(self.textBrowser)
        
        self.connect(self.mythread, SIGNAL("getoutput"),self.output)
        
        self.tipText = QLabel(self.tr("Student Computer Log"),self)
        self.tipText.setFont(QFont("times",15,QFont.Bold))
        self.tipText.move(5,5)
        
        
        self.mousePressed = False
    
    def updateWindow(self):
        self.tipText.setText(self.tr("Student Computer Log"))
        self.pauseButton.setText(self.tr("Pause"))
        self.mythread.start()
    
    def pauseThread(self):
        
        language = StoreInfoParser.instance().getLanguage()
        m_pTranslator = QTranslator()
        exePath = "./"
        if language == "chinese":
            QmName = "zh_CN.qm"
        else:
            QmName = "en_US.qm"
        if(m_pTranslator.load(QmName, exePath)):
            QCoreApplication.instance().installTranslator(m_pTranslator)
            
        if self.pauseButton.text() == self.tr("Pause"):
            self.mythread.stop()
            self.pauseButton.setText(self.tr("Restart"))
        elif self.pauseButton.text() == self.tr("Restart"):
            self.mythread.start()
            self.pauseButton.setText(self.tr("Pause"))
    def cancel(self):
        self.mythread.stop()
        self.close()
    def output(self, text):
        self.textBrowser.clear()
        self.textBrowser.setText(self.trUtf8(text))
        cursor = self.textBrowser.textCursor()
        cursor.movePosition(QTextCursor.End)
        self.textBrowser.setTextCursor(cursor)
        
    def mouseMoveEvent(self,event):
        if self.mousePressed:
            self.move(self.pos() + event.pos() - self.currentPos)   
        
    def mousePressEvent(self,event):
        if event.buttons() == Qt.LeftButton:
            self.currentPos = event.pos()
            self.mousePressed = True
    def mouseReleaseEvent(self,event):
        if event.buttons() == Qt.LeftButton:
            self.mousePressed = False
            
    def paintEvent(self,event):
        painter = QPainter(self)
        painter.save()
        linearGradient = QLinearGradient(0,0,0,self.geometry().width())
        linearGradient.setColorAt(0, QColor(60,150,255))
        linearGradient.setColorAt(0.1, QColor(6,88,200))
        linearGradient.setColorAt(1, QColor(80,150,255))
        painter.setBrush(QBrush(linearGradient))
        contenRect = QRect(0, 0, self.width(), self.topLine-10)
        painter.fillRect(contenRect, QBrush(linearGradient))
        painter.restore()
        
        painterBack = QPainter(self)
        backBrush = QBrush(QColor(200,200,250))
        painterBack.setBrush(backBrush)
        backRect = QRect(0,self.topLine-10,self.width(),self.height())
        painterBack.fillRect(backRect, backBrush)
class ComponentSearchForm():

    data_source = None   
    related_mashups = None
    widget = None
    table = None
    add_btn = None
    graph_form = None
    highlighted_api = None
    highlighted_mashup = None
    categoryWindow = None
    dataSetListWdiget = None
    climateData = None
    
    def show_main_window(self):
        # Get datasets from server
        data = json.load(urllib2.urlopen(RECO_API_SERVER_ADDR + "/getAllDataSets/"))
        # self.climateData = self.loadClimateDataSet(data)
        self.climateData = self.parseServerData(data)

        self.graph_form = matplotlibWidget()
        if self.widget:
            self.widget.destroy()
            self.widget = None;
        self.widget = QWidget()
        self.widget.setMinimumSize(1000, 900)
        self.widget.setWindowTitle("Recommendation PlugIn")
        margin = 30

        # Search Feature
        self.textboxLabel = QLabel(self.widget)
        self.textboxLabel.setText("Describe your goals:")
        self.textboxLabel.move(30, 20)
        self.textboxLabel.show
        self.textbox = QTextEdit(self.widget)
        self.textbox.move(30, 45)
        self.textbox.setFixedWidth(300)
        self.textbox.setFixedHeight(28)

        btn_api = QtGui.QPushButton("Recommend Services", self.widget)
        btn_api.move(30, 80)

        btn_mashup = QtGui.QPushButton("Recommend Workflows", self.widget)
        btn_mashup.move(230, 80)

        btn_api.clicked.connect(self.api_button_clicked)
        btn_mashup.clicked.connect(self.mashups_button_clicked)

        self.table = QTableView(self.widget)
        self.table.clicked.connect(self.table_clicked)
        self.table.setMinimumSize(600, 300)
        self.table.resizeColumnsToContents()
        self.table.move(30, 120)

        # Top Service
        self.textboxLabel = QLabel("Top Datasets (Usage)", self.widget)
        self.textboxLabel.move(650, 20)
        self.textboxLabel.show

        self.listWidget = QListWidget(self.widget)
        topDatasets = json.load(urllib2.urlopen(RECO_API_SERVER_ADDR + "/getTop10UsedDataset/"))
        for topDataset in topDatasets:
            id = int(topDataset["datasetID"])
            item = QListWidgetItem("{} ({})".format(self.climateData[id]["name"], topDataset["usage"]))
            item.setData(Qt.UserRole,self.climateData[id])
            self.listWidget.addItem(item)
        self.listWidget.move(650, 45)
        self.listWidget.resize(280, 380)
        self.listWidget.show()
        self.listWidget.clicked.connect(lambda: self.dataset_clicked(\
            self.listWidget.currentItem().data(Qt.UserRole)))


        # Username input box and button for generating recommendations
        userTopOffset = 430
        self.textboxLabel = QLabel("Enter username for dataset recommendations:", self.widget)
        self.textboxLabel.move(30, userTopOffset)
        self.textboxLabel.show()

        self.userTextbox = QTextEdit(self.widget)
        self.userTextbox.move(30, userTopOffset + 30)
        self.userTextbox.setFixedWidth(200)
        self.userTextbox.setFixedHeight(28)

        userBtn = QPushButton("Recommend Datasets", self.widget)
        userBtn.move(30 + self.userTextbox.width() + 10, userTopOffset + 30)
	#print RECO_API_SERVER_ADDR + "/getTop5RecommendationByUserName/"
	    
	    ## Jan.20 2016 
	    ##  Change the API names here by shenggu 
	    ##  According to github.com/cmusv-sc/RecommendationAPIs
	    ##
        userBtn.clicked.connect(lambda: self.getRecommendations(RECO_API_SERVER_ADDR + "/getTopKContentBasedCFRecommendedDatasetByUsername",
            self.recListFeature))
        userBtn.clicked.connect(lambda: self.getRecommendations(RECO_API_SERVER_ADDR + "/getTopKItemBasedCFRecommendedDatasetByUsername",
            self.recListItem))
        userBtn.clicked.connect(lambda: self.getRecommendations(RECO_API_SERVER_ADDR + "/getTopKUserBasedCFRecommendedDatasetByUsername",
            self.recListUser))
        userBtn.show()

        # Test QlineEdit
        # self.userTextbox2 = QLineEdit(self.widget)
        # self.userTextbox.move(200, userTopOffset + 30)
        # self.userTextbox.setFixedWidth(200)
        # self.userTextbox.setFixedHeight(28)

        # Feature Recommendations
        recTopOffset = 500
        self.textboxLabel = QLabel("Feature Recommendations", self.widget)
        self.textboxLabel.move(30, recTopOffset)
        self.textboxLabel.show()

        self.recListFeature = QListWidget(self.widget)
        self.recListFeature.move(30, recTopOffset + 30)
        self.recListFeature.resize(280, 250)
        self.recListFeature.show()

        # Item-based Recommendations
        self.textboxLabel = QLabel("Item-based Recommendations", self.widget)
        self.textboxLabel.move(340, recTopOffset)
        self.textboxLabel.show

        self.recListItem = QListWidget(self.widget)
        self.recListItem.move(340, recTopOffset + 30)
        self.recListItem.resize(280, 250)
        self.recListItem.show()

        # User-based Recommendations
        self.textboxLabel = QLabel("User-based Recommendations", self.widget)
        self.textboxLabel.move(650, recTopOffset)
        self.textboxLabel.show

        self.recListUser = QListWidget(self.widget)
        self.recListUser.move(650, recTopOffset + 30)
        self.recListUser.resize(280, 250)
        self.recListUser.show()

        # Categories
        categoryTopOffset = 300
        self.textboxLabel = QLabel("Categories", self.widget)
        self.textboxLabel.move(30, recTopOffset + categoryTopOffset)
        self.textboxLabel.show

        button1 = QPushButton("By Agency", self.widget)
        button1.clicked.connect(lambda: self.listCategory_clicked("agency"))
        button1.move(30, recTopOffset + categoryTopOffset + 30)
        button1.show()

        button2 = QPushButton("By Instrument", self.widget)
        button2.clicked.connect(lambda: self.listCategory_clicked("instrument"))
        button2.move(margin + button1.width() + 20, recTopOffset + categoryTopOffset + 30)
        button2.show()

        button3 = QPushButton("By Data Source Input", self.widget)
        button3.clicked.connect(lambda: self.listCategory_clicked("input"))
        button3.move(margin + button1.width() + button2.width() + 40, recTopOffset + categoryTopOffset + 30)
        button3.show()

        # Show and move widget
        self.widget.move(QtGui.QApplication.desktop().screen().rect().center() - \
            self.widget.rect().center())
        self.widget.show()

        # Service and workflow recommendation
        self.add_btn = QPushButton("Add to Palette", self.widget)
        self.add_btn.clicked.connect(self.add_new_api)
        self.add_btn.hide()
        self.add_btn.setFixedWidth(160)
        self.add_btn.move(470, 20)
        
        self.recommendLabel = QLabel("Also Used", self.widget)
        self.recommendLabel.hide()
        self.recommendLabel.setFixedWidth(160)
        self.recommendLabel.move(470, 50)
        
        self.switch_btn_apis = QPushButton("Related Workflows", self.widget)
        self.switch_btn_apis.clicked.connect(self._show_related_apis)
        self.switch_btn_apis.hide()
        self.switch_btn_apis.setFixedWidth(160)
        self.switch_btn_apis.move(470, 80)
        
        self.switch_btn_mashups = QPushButton("Related Modules", self.widget)
        self.switch_btn_mashups.clicked.connect(self._show_related_mashups)
        self.switch_btn_mashups.hide()
        self.switch_btn_mashups.setFixedWidth(160)
        self.switch_btn_mashups.move(470, 80)

    def printMessage(self):
        print "testing"

    def __init__(self, parent=None):
        self.data_source = DataSource()
    
    def getRecommendations(self, url, listWidget):
        # http GET request
        username = str(self.userTextbox.toPlainText())
        url = url + "?username=kzhang&top_num=5" #  + username
        print url
        results = json.load(urllib2.urlopen(url))
        
        # Update recommendation list
        listWidget.clear()
        for result in results:
            dataset = self.climateData[int(result["datasetID"])]
            item = QListWidgetItem(dataset["name"])
            item.setData(Qt.UserRole, dataset)
            listWidget.addItem(item)

        listWidget.clicked.connect(lambda: self.dataset_clicked(\
            listWidget.currentItem().data(Qt.UserRole)))

    def listCategory_clicked(self, category):
        self.categoryWindow = QWidget()
        c = self.categoryWindow
        c.setWindowTitle("Search dataset by category")
        c.setMinimumSize(600, 500)
        
        # Category list showing all posible options
        label1 = QLabel("Options by {0}:".format(category), c)
        label1.move(50, 20)
        label1.show()
        categoryListWidget = QListWidget(c)
        optionSet = set()
        for key in self.climateData:
            optionSet.add(self.climateData[key][category])
        for option in sorted(list(optionSet)):
            item = QListWidgetItem(option)
            item.setData(Qt.UserRole, option)
            categoryListWidget.addItem(item)
        categoryListWidget.move(50, 50)
        categoryListWidget.resize(200, 400)
        categoryListWidget.show()
        categoryListWidget.clicked.connect(lambda: self.categoryItem_clicked(\
            category, categoryListWidget.currentItem().data(Qt.UserRole)))

        # List showing all datasets associated with the selected option
        label2 = QLabel("Available Datasets:", c)
        label2.move(250, 20)
        label2.show()
        self.datasetListWidget = QListWidget(c)
        self.datasetListWidget.move(250, 50)
        self.datasetListWidget.resize(400, 400)
        self.datasetListWidget.show()

        c.move(QtGui.QApplication.desktop().screen().rect().center() - \
            c.rect().center())
        c.show()

    def categoryItem_clicked(self, category, option):
        self.datasetListWidget.clear()
        results = []
        for key in self.climateData:
            if self.climateData[key][category] == option:
                results.append(self.climateData[key])
        for result in sorted(results):
            item = QListWidgetItem(result["name"])
            item.setData(Qt.UserRole,result)
            self.datasetListWidget.addItem(item)
        self.datasetListWidget.clicked.connect(lambda: self.dataset_clicked(\
            self.datasetListWidget.currentItem().data(Qt.UserRole)));


    def dataset_clicked(self, data):
        # Initiate Table
        keyOrder = ["name", "agency", "instrument", "pvar", "var", "units", "grid", \
        "webvar", "input", "start", "end"]
        sortedData = sorted(data.items(), key=lambda dataPair:keyOrder.index(dataPair[0]))
        self.topServiceTable = QTableWidget()
        t = self.topServiceTable
        t.setWindowTitle(data["name"])
        t.resize(550, 400)
        t.setRowCount(len(data.keys()))
        t.setColumnCount(2)
        t.setColumnWidth(0, 100);
        t.setColumnWidth(1, 400);

        # Set label
        t.setHorizontalHeaderLabels(("Variable;Value").split(";"))

        # Set data
        for row, pair in enumerate(sortedData):
            t.setItem(row, 0, QTableWidgetItem(pair[0]))
            t.setItem(row, 1, QTableWidgetItem(pair[1]))

        t.move(QtGui.QApplication.desktop().screen().rect().topRight() - t.rect().topRight())
        t.show()


    def table_clicked(self):
        """
        Click the table, the graph form may change according to the selection.
        """
        model = self.table.selectionModel()
        indexes = model.selectedIndexes()
        for index in indexes:
            row = index.row()
            #            data = index.model().headerData(0,Qt.Horizontal).toString()
            data = index.model().headerData(0,Qt.Horizontal)
            newIndex = index.model().index(row, 0)
            if data == "API":
                api_id = get_api_full_name(newIndex.model().data(newIndex))
                api = self.data_source.api_by_id(api_id)
                print api
                mashups = self.data_source.mashups_by_api(api)
                apis = []
                for mashup in mashups:
                    apis.extend(self.data_source.apis_by_mashup(mashup))
                self.graph_form.draw_apis(apis, api, self.highlighted_api)
            else:
                mashup_id = get_mashup_full_name(newIndex.model().data(newIndex))
                mashup = self.data_source.mashup_by_id(mashup_id)
                if not mashup:
                    return
                apis = self.data_source.apis_by_mashup(mashup)
                mashups = []
                if len(apis) > 0:
                    mashups.extend(self.data_source.mashups_by_api(apis[0]))
                self.graph_form.draw_mashups(mashups, mashup, self.highlighted_mashup)
            return


    def _show_apis(self, apis, recommend=False):
        self.switch_btn_apis.hide()
        self.switch_btn_mashups.hide()
        self.recommendLabel.hide()

        row = 0
        model = QStandardItemModel(len(apis), 4)
        model.setColumnCount(4)
        #QVariant(...) -> ...
        for api in apis:
            model.setData(model.index(row, 0), get_api_name(api))
            model.setData(model.index(row, 1), api['protocols'])
            model.setData(model.index(row, 2), api['provider'])
            model.setData(model.index(row, 3), api['version'])
            row += 1

        model.setHeaderData(0, Qt.Horizontal, "Service") # Replaced "Module" with "Service"
        model.setHeaderData(1, Qt.Horizontal, "Protocol")
        model.setHeaderData(2, Qt.Horizontal, "Provider")
        model.setHeaderData(3, Qt.Horizontal, "Version")

        self.table.setModel(model)
        self.table.resizeColumnsToContents()
        
        if recommend:
            self.recommendLabel.show()
        
        self.add_btn.show()

    def _show_mashups(self, mashups):
        self.switch_btn_apis.hide()
        self.switch_btn_mashups.hide()
        self.recommendLabel.hide()
        row = 0
        model = QStandardItemModel(len(mashups), 4)
        model.setColumnCount(4)
        for mashup in mashups:
            model.setData(model.index(row, 0), get_mashup_name(mashup))
            model.setData(model.index(row, 1), mashup['title'])
            model.setData(model.index(row, 2), mashup['self'])
            model.setData(model.index(row, 3), mashup['description'])
            
            row += 1
        
        model.setHeaderData(0, Qt.Horizontal, "Workflow")
        model.setHeaderData(1, Qt.Horizontal, "Short Description")
        model.setHeaderData(2, Qt.Horizontal, "Provider")
        model.setHeaderData(3, Qt.Horizontal, "Detailed Info")

        self.table.setModel(model)
        self.table.resizeColumnsToContents()
        self.add_btn.show()

    def api_button_clicked(self):
        """
        Trigger to search APIs
        """        
        self.graph_form.draw_api()
        self.graph_form.show()

        # Get user input from textbox
        apis = self.data_source.apis()
        key = str(self.textbox.toPlainText())
        if key:
            self.api_search_button_clicked()
        else:
            self._show_apis(apis)

    def mashups_button_clicked(self):
        """
        Trigger to search mashups
        """
        self.graph_form.draw_mashup()
        self.graph_form.show()

        key = str(self.textbox.toPlainText())
        print key
        print "button clicked"
        if key:
            self.mashup_search_button_clicked()
        else:
            self._show_mashups(self.data_source.mashups())

    #Should probably refactor this into one method.
    def api_search_button_clicked(self):
        """
        Search when keyword is present
        """
        self.highlighted_api = None
        self.highlighted_mashup = None
        key = str(self.textbox.toPlainText())
        if key != "":
            apis = self.data_source.search_api(key)
            self._show_apis(apis)

    def mashup_search_button_clicked(self):
        """
        Search when keyword is present
        """
        self.highlighted_api = None
        self.highlighted_mashup = None
        key = str(self.textbox.toPlainText())
        if key != "":
            mashups = self.data_source.search_mashup(key)
            self._show_mashups(mashups)
    
    def add_new_api(self):
        """
        Add new api to the modules package.
        """
        apis = self.data_source.apis()
        model = self.table.selectionModel()
        indexes = model.selectedIndexes()
        for index in indexes:
            api = apis[index.row()]
            self._add_new_api(api)
            return
    
    def add_related_api(self):
        objs = []
        for mashup in self.related_mashups:
            objs.append(mashup)
            for api in mashup["related_mashups"]:
                objs.append(api)
        model = self.table.selectionModel()
        indexes = model.selectedIndexes()
        for index in indexes:
            api = objs[index.row()]
            if api.get("protocols"):
                self._add_new_api(api)
                return

    def _show_related_mashups(self):
        self.switch_btn_apis.hide()
        self.switch_btn_mashups.hide()
        self.recommendLabel.hide()
        
        apis = []
        objs = []
        for mashup in self.related_mashups:
            apis.extend(mashup["related_mashups"])

        for api in apis:
            objs.append(api)
            mashups = self.data_source.mashups_by_api(api)
            objs.extend(mashups)

        row = 0
        model = QStandardItemModel(len(objs), 4)
        model.setColumnCount(4)
        for obj in objs:
            if obj.get('protocols'):
                model.setData(model.index(row, 0), get_api_name(obj))
                model.setData(model.index(row, 1), obj['protocols'])
                model.setData(model.index(row, 2), obj['provider'])
            else:
                model.setData(model.index(row, 3), get_mashup_name(obj))
            row += 1

        model.setHeaderData(0, Qt.Horizontal, "API")
        model.setHeaderData(1, Qt.Horizontal, "Protocols")
        model.setHeaderData(2, Qt.Horizontal, "Provider")
        model.setHeaderData(3, Qt.Horizontal, "Mashup")
        self.table.setModel(model)
        self.table.resizeColumnsToContents()
        self.switch_btn_apis.show()

    def _show_related_apis(self):
        self.switch_btn_apis.hide()
        self.switch_btn_mashups.hide()
        self.recommendLabel.hide()
        
        row = 0
        objs = []
        for mashup in self.related_mashups:
            objs.append(mashup)
            for api in mashup["related_mashups"]:
                objs.append(api)
        #Combining similarity and related.
        similar_apis = self.data_source.search_api_similarity(self.highlighted_api)
        #return str(mashup['id'])[(len("http://www.programmableweb.com/mashup/")):]
        objs.append({'id': "http://www.programmableweb.com/mashup/Using-Similarity-Metric"})
        objs.extend(similar_apis)
        #Combining similarity and related.

        #http://localhost:9000/getReputation/John%20Lions
        model = QStandardItemModel(len(objs), 6)
        for obj in objs:
            if obj.get('protocols'):
                model.setData(model.index(row, 1), get_api_name(obj))
                model.setData(model.index(row, 2), obj['protocols'])
                model.setData(model.index(row, 3), obj['provider'])
                model.setData(model.index(row, 4), obj['version'])
                #trust  = requests.get('http://localhost:9000/getReputation/Luis Ramos').content
                model.setData(model.index(row, 5), str(random.random()))
                #model.setData(model.index(row, 5), QVariant(trust))
            else:
                model.setData(model.index(row, 0), get_mashup_name(obj))
            row += 1

        model.setHeaderData(0, Qt.Horizontal, "Mashup")
        model.setHeaderData(1, Qt.Horizontal, "API")
        model.setHeaderData(2, Qt.Horizontal, "Protocols")
        model.setHeaderData(3, Qt.Horizontal, "Provider")
        model.setHeaderData(4, Qt.Horizontal, "Version")
        model.setHeaderData(5, Qt.Horizontal, "Trust")

        self.table.setModel(model)
        self.table.resizeColumnsToContents()
        self.switch_btn_mashups.show()

    def _add_new_api(self, api):
        self.highlighted_api = api
        mashups = self.data_source.mashups_by_api(api)
        for mashup in mashups:
            mashup['related_mashups'] = (self.data_source.apis_by_mashup(mashup))
        if len(mashups) > 0:
            self.related_mashups = mashups
            self._show_related_apis()
        manager = core.packagemanager.get_package_manager()
        reg = core.modules.module_registry.get_module_registry()
        package = manager.get_package("edu.cmu.sv.components", "1.0.0")
        core.modules.module_registry.set_current_package(package)

        if (api["protocols"] == "SOAP" and api["wsdl"] != ""):
            s = Service(api["wsdl"])
#            add_new_service(s, api["wsdl"])
        else:
            new_module = vistrails_module.new_module(Module, get_api_name(api))
            reg.add_module(new_module)
    
            reg.add_input_port(new_module, "value1",
                         (core.modules.basic_modules.String, 'the first argument'))
            reg.add_input_port(new_module, "value2",
                         (core.modules.basic_modules.String, 'the second argument'))
            reg.add_output_port(new_module, "value",
                          (core.modules.basic_modules.String, 'the result'))

    # def loadClimateDataSet(self):
    #     filename = '/home/hywel/Documents/VisTrailsRecommendation/vistrails_current/vistrails/packages/componentSearch/Climate_Datasets.csv'
    #     with open(filename, mode='r') as infile:
    #         reader = csv.reader(infile)
    #         next(reader, None)
    #         with open('coors_new.csv', mode='w') as outfile:
    #             writer = csv.writer(outfile)
    #             climateData = {}
    #             for row in reader:
    #                 id = int(row[0])
    #                 climateData[id] = {}
    #                 climateData[id]["dataset"] = row[1]
    #                 climateData[id]["agency"] = row[2]
    #                 climateData[id]["instrument"] = row[3]
    #                 climateData[id]["pvar"] = row[4]
    #                 climateData[id]["var"] = row[5]
    #                 climateData[id]["units"] = row[6]
    #                 climateData[id]["grid"] = row[7]
    #                 climateData[id]["webvar"] = row[8]
    #                 climateData[id]["input"] = row[9]
    #                 climateData[id]["start"] = row[10]
    #                 climateData[id]["end"] = row[11]
    #     return climateData

    def parseServerData(self, data):
        climateData = {}
        for dataset in data:
            id = int(dataset["datasetID"])
            climateData[id] = {}
            climateData[id]["name"] = dataset["dataset"]
            climateData[id]["agency"] = dataset["agency"]
            climateData[id]["instrument"] = dataset["instrument"]
            climateData[id]["pvar"] = dataset["pvar"]
            climateData[id]["var"] = dataset["var"]
            climateData[id]["units"] = dataset["units"]
            climateData[id]["grid"] = dataset["grid"]
            climateData[id]["webvar"] = dataset["webvar"]
            climateData[id]["input"] = dataset["input"]
            climateData[id]["start"] = dataset["start"]
            climateData[id]["end"] = dataset["end"]
        return climateData
Exemplo n.º 39
0
    def __init__(self, controller):
        QDialog.__init__(self, controller.main_widget, Qt.Dialog)
        self.setAttribute(Qt.WA_Maemo5StackedWindow)
        self.setWindowTitle("About DropN900")
        
        grid_layout = QGridLayout()
        grid_layout.setVerticalSpacing(5)
        grid_layout.setHorizontalSpacing(25)
        grid_layout.setContentsMargins(0, 10, 50, 0)
        self.setLayout(grid_layout)

        icon_label = QLabel(self)
        icon_label.setMinimumSize(128, 128)
        icon_label.setMaximumSize(128, 128)
        icon_label.setPixmap(QPixmap(controller.datahandler.datapath("ui/images/dropn900_logo.png")))
        icon_label.move(600, 5)
        
        topics = []           
        links = []
        
        label = QLabel("Version")
        topics.append(label)        
        self.layout().addWidget(label, 0, 0, Qt.AlignRight)
        
        label = QLabel("0.1.8")
        self.layout().addWidget(label, 0, 1)
                
        label = QLabel("Made by")
        topics.append(label)        
        self.layout().addWidget(label, 1, 0, Qt.AlignRight)
        
        label = QLabel("Jonne Nauha")
        self.layout().addWidget(label, 1, 1)

        label = QLabel("Pforce @ IRCNet & freenode")
        self.layout().addWidget(label, 2, 1)
        
        label = QPushButton("*****@*****.**")
        label.clicked.connect(self.email_clicked)
        label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        links.append(label)
        self.layout().addWidget(label, 3, 1)
        
        label = QLabel("Official Thread")
        topics.append(label)       
        self.layout().addWidget(label, 4, 0, Qt.AlignRight)
        
        label = QPushButton("http://talk.maemo.org/showthread.php?t=58882")
        label.clicked.connect(self.thread_clicked)
        label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        links.append(label)
        self.layout().addWidget(label, 4, 1)
        
        label = QLabel("Bug tracker")
        topics.append(label)       
        self.layout().addWidget(label, 5, 0, Qt.AlignRight)
        
        label = QPushButton("http://github.com/jonnenauha/DropN900/issues")
        label.clicked.connect(self.tracker_clicked)
        label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        links.append(label)
        self.layout().addWidget(label, 5, 1)
        
        label = QLabel("Icons")
        topics.append(label)       
        self.layout().addWidget(label, 6, 0, Qt.AlignRight)
        
        label = QPushButton("http://openiconlibrary.sourceforge.net")
        label.clicked.connect(self.icons_clicked)
        label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        links.append(label)
        self.layout().addWidget(label, 6, 1)
                
        label = QLabel("Donate")
        topics.append(label)       
        self.layout().addWidget(label, 7, 0, Qt.AlignRight)
        
        label = QLabel("Paypal with above email or click")
        self.layout().addWidget(label, 7, 1)
        
        button = QPushButton()
        button.clicked.connect(self.donate_clicked)
        button.setMinimumSize(160, 70)
        button.setMaximumSize(160, 70)
        button.setStyleSheet("QPushButton { background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(37, 37, 37, 255), \
                              stop:0.542714 rgba(66, 66, 66, 255), stop:1 rgba(39, 39, 39, 255)); border: 2px solid grey; border-radius: 15px; background-repeat: no-repeat; \
                              background-position: center center; background-image: url(" + controller.datahandler.datapath("ui/images/paypal.gif") + ") } \
                              QPushButton:pressed { background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(37, 37, 37, 255), \
                              stop:0.542714 rgba(118, 118, 118, 255), stop:1 rgba(39, 39, 39, 255)); border: 2px solid white; }")        
        self.layout().addWidget(button, 7, 1, Qt.AlignRight)
        self.layout().setRowMinimumHeight(7, 200)
        
        style = "QLabel { color: #0099FF; }"
        for topic in topics:
            topic.setStyleSheet(style)
            
        # Cant seem to change color of links no matter what
        style = "QPushButton { background-color: transparent; border: 0px; text-decoration: underline; } \
                 QPushButton:pressed { color: #0099FF; }"
        for link in links:
            link.setStyleSheet(style)
Exemplo n.º 40
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.agreement1ID = 'AG01'
        self.agreement2ID = 'AG02'
        self.dbNameInit = 'test1'
        self.calculate1 = '+'
        self.c1 = '1'
        self.c3 = '1'
        self.threads = []
        self.onInit()

    def onInit(self):
        self.resize(450, 300)
        self.center()
        self.setMenu()
        self.setWindowTitle(u'MainWindow')
        self.setWindowIcon(QIcon('learning.ico'))

        self.agreement1 = QLabel('Contract1', self)
        self.agreement11 = QLabel('      Contract1 *', self)

        self.agreement2 = QLabel('Contract2', self)
        self.agreement22 = QLabel('Contract2 *', self)
        self.calculate = QLabel('Formula', self)
        self.startTime = QLabel('Start Time', self)
        self.endTime = QLabel('End Time', self)
        self.agreement1Edit = QLineEdit()
        self.agreement2Edit = QLineEdit()
        self.calculate1Edit = QLineEdit()
        self.calculate2Combo = QComboBox()
        self.calculate2Combo.addItem('+')
        self.calculate2Combo.addItem('-')
        self.calculate2Combo.addItem('*')
        self.calculate2Combo.addItem('/')

        self.calculate2Combo.activated[str].connect(self.onActivated)

        self.calculate2Edit = QLineEdit()
        self.calculate3Edit = QLineEdit()
        self.startTimeEdit = QDateTimeEdit(
            datetime.strptime('20150101 00:00:00', '%Y%m%d %H:%M:%S'), self)
        self.startTimeEdit.setDisplayFormat('yyyy-MM-dd')
        self.startTimeEdit.setCalendarPopup(True)
        self.endTimeEdit = QDateTimeEdit(QDateTime.currentDateTime(), self)
        self.endTimeEdit.setDisplayFormat('yyyy-MM-dd')
        self.endTimeEdit.setCalendarPopup(True)
        self.stateEdit = QTextEdit()

        self.run = QPushButton('Run', self)
        self.run.clicked.connect(self.runMain)
        #self.setAgreementBtn = QPushButton('Setting', self)
        #self.setAgreementBtn.clicked.connect(self.setAgreement)

        grid = QGridLayout()
        #grid.setSpacing(10)
        grid.addWidget(self.agreement1, 1, 0)
        grid.addWidget(self.agreement1Edit, 1, 1)
        grid.addWidget(self.agreement2, 2, 0)
        grid.addWidget(self.agreement2Edit, 2, 1)
        #grid.addWidget(self.setAgreementBtn, 2, 2)
        grid.addWidget(self.startTime, 3, 0)
        grid.addWidget(self.startTimeEdit, 3, 1)
        grid.addWidget(self.endTime, 4, 0)
        grid.addWidget(self.endTimeEdit, 4, 1)
        grid.addWidget(self.calculate, 5, 0)
        grid.addWidget(self.agreement11, 5, 1)
        grid.addWidget(self.calculate1Edit, 5, 2)
        grid.addWidget(self.calculate2Combo, 5, 3)
        grid.addWidget(self.agreement22, 5, 4)
        grid.addWidget(self.calculate3Edit, 5, 5)
        grid.addWidget(self.stateEdit, 6, 1, 1, 5)
        grid.addWidget(self.run, 7, 1)
        gridWidget = QWidget()
        gridWidget.setLayout(grid)
        self.agreement11.move(200, 100)
        self.setCentralWidget(gridWidget)
        self.show()

    def onActivated(self, text):
        self.calculate1 = text

    def setMenu(self):
        exitAction = QAction(u'Quit', self)
        exitAction.triggered.connect(qApp.quit)

        menubar = self.menuBar()
        fileMenu = menubar.addMenu(u'Menu')
        fileMenu.addAction(exitAction)

    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def done(self, ls):
        self.stateEdit.append(u'Maximum:%f' % ls[1])
        self.stateEdit.append(u'Minimum:%f' % ls[2])
        self.stateEdit.append(u'Average:%f' % ls[3])
        show(ls[0])
        self.run.setEnabled(True)
        self.stateEdit.append('End time: %s' % time.ctime())

    def runMain(self):
        self.run.setEnabled(False)
        agreementt1 = self.agreement1Edit.text()
        agreementt2 = self.agreement2Edit.text()
        if agreementt1 == '':
            self.stateEdit.append('Settings of contract1 have error!')
        elif agreementt2 == '':
            self.stateEdit.append('Settings of contract2 have error!')
        else:
            self.agreement1ID = agreementt1
            self.agreement2ID = agreementt2
        startTime = self.startTimeEdit.dateTime()
        endTime = self.endTimeEdit.dateTime()
        self.c1 = self.calculate1Edit.text()
        self.c3 = self.calculate3Edit.text()
        self.stateEdit.append('Formula: ' + self.c1 + '*' + self.agreement1ID +
                              self.calculate1 + self.c3 + '*' +
                              self.agreement2ID + ' have set')
        self.stateEdit.append('Start time: %s' % time.ctime())
        self.workThread = WorkThread(self.agreement1ID, self.agreement2ID,
                                     startTime, endTime, self.c1, self.c3,
                                     self.calculate1)
        self.workThread.finishSignal.connect(self.done)
        self.workThread.start()
Exemplo n.º 41
0
class ChampionTab(QLabel):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.resize(670, 50)
        self.setStyleSheet(
            "QLabel {color: black; background-color: gold; border-radius:10px}"
        )

        self.champPic = QLabel(self)
        self.champPic.setScaledContents(True)
        self.champPic.resize(40, 40)
        self.champPic.move(5, 5)

        self.champName = QLabel(self)
        self.champName.setStyleSheet("QLabel {font: 14px}")
        self.champName.resize(100, 40)
        self.champName.move(46, 5)

        self.numOfSessions = QLabel(self)
        self.numOfSessions.setAlignment(Qt.AlignCenter)
        self.numOfSessions.resize(40, 40)
        self.numOfSessions.move(147, 5)

        self.winRatio = QLabel(self)
        self.winRatio.setAlignment(Qt.AlignCenter)
        self.winRatio.resize(60, 40)
        self.winRatio.move(188, 5)

        self.kda = QLabel(self)
        self.kda.setAlignment(Qt.AlignCenter)
        self.kda.resize(200, 40)
        self.kda.move(249, 5)

        self.cs = QLabel(self)
        self.cs.setAlignment(Qt.AlignCenter)
        self.cs.resize(60, 40)
        self.cs.move(450, 5)

    def setIcon(self, champIcon):
        self.champPic.setPixmap(champIcon)

    def setName(self, name):
        self.champName.setText(name)

    def setNumOfSessions(self, num):
        self.numOfSessions.setText(str(num))

    def setWinRatio(self, winRate):
        self.winRatio.setText(str(winRate) + '%')

    def setKDA(self, kills, deaths, assists):
        self.kda.setText(
            str(kills) + " / " + str(deaths) + " / " + str(assists))

    def setCS(self, cs):
        self.cs.setText(str(cs))
Exemplo n.º 42
0
class entrar(QDialog):
    def __init__(self):

        super(entrar, self).__init__(None)

        self.resize(400, 440)
        self.setWindowTitle('Datos de Usuario')

        self.imaje = QLabel(self)
        self.imaje.setGeometry(160, 210, 225, 225)
        self.imaje.setPixmap(QPixmap(getcwd() + "/usuario.gif"))

        self.n = QLabel('Nombre Completo:', self)
        self.n.move(10, 10)

        self.u = QLabel('Nombre de Usuario:', self)
        self.u.move(10, 50)

        self.failu = QLabel('Este Usuario ya Existe', self)
        self.failu.move(140, 70)
        self.failu.hide()

        self.c = QLabel('Correo Electronico:', self)
        self.c.move(10, 90)

        self.a = QLabel('Edad:', self)
        self.a.move(10, 130)

        self.faila = QLabel('Ingrese una Edad', self)
        self.faila.move(140, 150)
        self.faila.hide()

        self.p = QLabel('Clave:', self)
        self.p.move(10, 170)

        self.failp = QLabel('Clave muy Debil', self)
        self.failp.move(140, 190)
        self.failp.hide()

        self.f = QLabel('Foto:', self)
        self.f.move(10, 210)

        self.Name = QLineEdit(self)
        self.Name.setGeometry(140, 10, 200, 20)

        self.User = QLineEdit(self)
        self.User.setGeometry(140, 50, 200, 20)

        self.Mail = QLineEdit(self)
        self.Mail.setGeometry(140, 90, 200, 20)

        self.Age = QLineEdit(self)
        self.Age.setGeometry(140, 130, 200, 20)

        self.Pass = QLineEdit(self)
        self.Pass.setGeometry(140, 170, 200, 20)

        self.buscarfoto = QPushButton('Buscar Foto', self)
        self.buscarfoto.setGeometry(10, 250, 100, 30)

        self.guardar = QPushButton('Guardar', self)
        self.guardar.setGeometry(30, 300, 60, 30)

        self.failc = QLabel('Llenar Campos Vacios', self)
        self.failc.move(10, 350)
        self.failc.hide()

        self.connect(self.buscarfoto, SIGNAL('clicked()'),
                     lambda: self.buscar())
        self.connect(
            self.guardar, SIGNAL('clicked()'), lambda: self.nuevo(
                self.Name, self.User, self.Mail, self.Age, self.Pass))
        #sys.exit(self.editar.exec_())

    def ponfoto(self, a):
        self.imaje.hide()
        #self.imaje.setPixmap(QPixmap(a))

    def buscar(self):
        e = explorador()
        e.exec_()

    def nuevo(self, name, user, mail, age, passw):
        n = name.text()
        u = user.text()
        m = mail.text()
        a = age.text()
        p = passw.text()

        if (n != '' and u != '' and m != '' and a != ''
                and p != ''):  #revisa que todos los campos esten llenos
            login = open('login.txt', 'r')
            self.failc.hide()

            for i in login:
                if str(u) in i:  # revisa si ya existe este nombre de usuario
                    self.failu.show()

                else:
                    self.failu.hide()

                    try:  # revisa si se ingresa un numero
                        int(a)
                        self.faila.hide()
                        usuarios = open('usuarios.txt', 'a')
                        usuarios.write(n + ',' + u + ',' + m + ',' + a + ',' +
                                       p + '\n')
                        usuarios.close()

                    except ValueError:
                        self.faila.show()

            login.close()

        else:
            self.failc.show()
Exemplo n.º 43
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.clean_up_queue = []
        self.summoner = SummonerData()
        self.summoner.getStaticData()

        ### Search Bar ###
        ##################

        #label
        self.search_label = QLabel(self)
        self.search_label.move(20, 15)
        self.search_label.resize(220, 25)
        self.search_label.setText('Enter summoner name(s):')
        self.search_label.setStyleSheet("QLabel {font:14pt}")

        #text field
        self.search_field = QLineEdit(self)
        self.search_field.move(260, 15)
        self.search_field.resize(250, 25)
        self.search_field.setPlaceholderText("ex: mcnuggets, teltor, ...")
        self.search_field.setFocusPolicy(Qt.ClickFocus)

        #search button
        self.search_button = QPushButton(self)
        self.search_button.move(520, 15)
        self.search_button.resize(150, 25)
        self.search_button.setText('Search Summoner')

        #region combobox
        self.region_list = QComboBox(self)
        self.region_list.move(680, 15)
        self.region_list.resize(75, 25)
        regions = ['NA', 'LAN', 'BR', 'LAS', 'EUW', 'EUNE', 'TR', 'RU', 'OCE']
        self.region_list.addItems(regions)

        #error label
        self.error_label = QLabel(self)
        self.error_label.move(775, 15)
        self.error_label.resize(160, 25)
        self.error_label.setStyleSheet("QLabel {font:14pt}")

        ### Summoner Information ###
        ############################

        #summoner Icon label
        self.icon_label = QLabel(self)
        self.icon_label.setScaledContents(True)
        self.icon_label.move(260, 50)
        self.icon_label.resize(110, 110)

        #name label
        self.name_label = QLabel(self)
        self.name_label.move(380, 50)
        self.name_label.resize(620, 50)
        self.name_label.setText('SUMMONER NAME')
        self.name_label.setStyleSheet("QLabel {font:32pt}")

        #rank label
        self.rank_label = QLabel(self)
        self.rank_label.move(380, 100)
        self.rank_label.resize(200, 60)
        self.rank_label.setText('summoner rank')
        self.rank_label.setStyleSheet("QLabel {font:18pt}")

        #miniseries labels
        self.series_labels = {}
        self.pixmap_win = QPixmap()
        self.pixmap_loss = QPixmap()
        self.pixmap_n = QPixmap()
        self.pixmap_win.load("./images/win.png")
        self.pixmap_loss.load("./images/loss.png")
        self.pixmap_n.load("./images/n.png")
        xPos = 600
        for x in range(5):
            match_label = QLabel(self)
            match_label.move(xPos, 120)
            match_label.resize(35, 35)
            match_label.setScaledContents(True)
            match_label.hide()
            self.series_labels[x] = match_label
            xPos += 40

        #mastery image labels
        print 'loading mastery images ...'
        self.ferocity_tree_images = self.getMasteryImages(
            self.summoner.ferocityMasteryTree())
        self.cunning_tree_images = self.getMasteryImages(
            self.summoner.cunningMasteryTree())
        self.resolve_tree_images = self.getMasteryImages(
            self.summoner.resolveMasteryTree())
        print 'Done'

        #champion icon image labels
        print 'loading champion icon images ...'
        self.championIcons = self.getChampionIconImages(
            self.summoner.championList())
        print 'Done'

        #overview widget
        self.overview_widget = QWidget()
        self.overview_menu = QTabWidget(self.overview_widget)
        self.overview_menu.resize(720, 270)

        #runes widget
        self.runes_widget = QWidget()
        self.runes_menu = QTabWidget(self.runes_widget)
        self.runes_menu.resize(720, 270)

        #masteries widget
        self.masteries_widget = QWidget()
        self.masteries_menu = QTabWidget(self.masteries_widget)
        self.masteries_menu.resize(720, 270)

        #summoner menu
        self.menu = QTabWidget(self)
        self.menu.move(260, 180)
        self.menu.resize(720, 300)
        self.menu.addTab(self.overview_widget, "Overview")
        self.menu.addTab(self.runes_widget, "Runes")
        self.menu.addTab(self.masteries_widget, "Masteries")
        self.menu.hide()

        #summoners buttons
        self.button_list = {}
        yPos = 150
        for x in range(10):
            sum_button = QPushButton(self)
            sum_button.move(50, yPos)
            sum_button.resize(150, 25)
            sum_button.hide()
            self.button_list[x] = sum_button
            yPos += 25

        ### Connecting Widgets ###
        ##########################

        self.connect(self.search_button, QtCore.SIGNAL("clicked()"),
                     self.getData)
        self.connect(self.search_button, QtCore.SIGNAL("clicked()"),
                     self.getRankedData)
        self.connect(self.button_list[0], QtCore.SIGNAL("clicked()"),
                     lambda: self.displayData(str(self.button_list[0].text())))
        self.connect(self.button_list[1], QtCore.SIGNAL("clicked()"),
                     lambda: self.displayData(str(self.button_list[1].text())))
        self.connect(self.button_list[2], QtCore.SIGNAL("clicked()"),
                     lambda: self.displayData(str(self.button_list[2].text())))
        self.connect(self.button_list[3], QtCore.SIGNAL("clicked()"),
                     lambda: self.displayData(str(self.button_list[3].text())))
        self.connect(self.button_list[4], QtCore.SIGNAL("clicked()"),
                     lambda: self.displayData(str(self.button_list[4].text())))
        self.connect(self.button_list[5], QtCore.SIGNAL("clicked()"),
                     lambda: self.displayData(str(self.button_list[5].text())))
        self.connect(self.button_list[6], QtCore.SIGNAL("clicked()"),
                     lambda: self.displayData(str(self.button_list[6].text())))
        self.connect(self.button_list[7], QtCore.SIGNAL("clicked()"),
                     lambda: self.displayData(str(self.button_list[7].text())))
        self.connect(self.button_list[8], QtCore.SIGNAL("clicked()"),
                     lambda: self.displayData(str(self.button_list[8].text())))
        self.connect(self.button_list[9], QtCore.SIGNAL("clicked()"),
                     lambda: self.displayData(str(self.button_list[9].text())))

        ### Window Configuration ###
        ############################

        #window settings
        self.setGeometry(200, 150, 1000, 500)
        self.setMaximumSize(1000, 500)
        self.setWindowTitle('summoner App')

        self.show()
Exemplo n.º 44
0
class main(QMainWindow):

    def __init__(self):
        QMainWindow.__init__(self)
        self.setWindowTitle("Images!")

    ## Create BackGround to Load images into

        self.bg = QLabel(self)
        self.bg.move(0, 30)
        self.bg.resize(400, 550)
        self.bg.setStyleSheet("background-color: black;")
        self.setGeometry(100, 100, 400, 600)

        self.button = QLabel("Open..", self)
        self.button.setFixedSize(55, 24)
        self.button.setStyleSheet("border: 1px solid black; font-size: 15px")
        self.button. move(330, 2)
        self.button.mousePressEvent = self.open_label

    ## Create File QAction for MenuBar

        openFileAction = QAction('&Open Image...', self)
        openFileAction.setShortcut('Ctrl+O')
        openFileAction.setStatusTip('Open Image File')

    ## Connect to the open_image function

        openFileAction.triggered.connect(self.open_file)

    #Exit Action

        exitAction = QAction('Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.triggered.connect(app.quit)

    ## Create Menu Bar and Add File Menu to it

        self.menubar = self.menuBar()
        self.file_menu = self.menubar.addMenu("&File")

    ## Link the File Menu to the QActions.

        self.file_menu.addAction(openFileAction)
        self.file_menu.addAction(exitAction)

    def open_label(self, event):

        self.open_file()

    def open_file(self):

        filename = QFileDialog.getOpenFileName()
        print filename

     ## import Image as a QPixMap

        self.bg_img = QPixmap(filename)

    ## Resize Window to the Size of opened image

        self.setFixedSize(self.bg_img.size())  #<---~ 'self is the QMainWindow'
        self.bg.setFixedSize(self.bg_img.size())


    ## set the Image to the background QLabel

        self.bg.setPixmap(self.bg_img)

        self.button.move(int(self.bg_img.width()) - 70, 2)
Exemplo n.º 45
0
class MasteryWidget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.mastery_rank_labels = {}

        #mastery page name label
        self.page_name = QLabel(self)
        self.page_name.resize(500, 25)

        #ferocity tree label
        self.ferocity_tree = QLabel(self)
        self.ferocity_tree.move(7, 25)
        self.ferocity_tree.resize(230, 211)
        self.ferocity_tree.setStyleSheet(
            "QLabel {color:black; background-color:maroon; border-style: outset; border-width: 2px; border-color: black}"
        )
        self.total_ferocity_points = QLabel(self.ferocity_tree)
        self.total_ferocity_points.move(175, 178)
        self.total_ferocity_points.resize(30, 30)
        self.total_ferocity_points.setAlignment(Qt.AlignCenter)
        self.total_ferocity_points.setStyleSheet(
            "QLabel {color:black; background-color:white; border-radius:10px; font: bold 14px}"
        )

        #cunning tree label
        self.cunning_tree = QLabel(self)
        self.cunning_tree.move(242, 25)
        self.cunning_tree.resize(230, 211)
        self.cunning_tree.setStyleSheet(
            "QLabel {color:black; background-color:navy; border-style: outset; border-width: 2px; border-color: black}"
        )
        self.total_cunning_points = QLabel(self.cunning_tree)
        self.total_cunning_points.move(175, 178)
        self.total_cunning_points.resize(30, 30)
        self.total_cunning_points.setAlignment(Qt.AlignCenter)
        self.total_cunning_points.setStyleSheet(
            "QLabel {color:black; background-color:white; border-radius:10px; font: bold 14px}"
        )

        #resolve tree label
        self.resolve_tree = QLabel(self)
        self.resolve_tree.move(477, 25)
        self.resolve_tree.resize(230, 211)
        self.resolve_tree.setStyleSheet(
            "QLabel {color:black; background-color:green; border-style: outset; border-width: 2px; border-color: black}"
        )
        self.total_resolve_points = QLabel(self.resolve_tree)
        self.total_resolve_points.move(175, 178)
        self.total_resolve_points.resize(30, 30)
        self.total_resolve_points.setAlignment(Qt.AlignCenter)
        self.total_resolve_points.setStyleSheet(
            "QLabel {color:black; background-color:white; border-radius:10px; font: bold 14px}"
        )

    def setName(self, name):
        self.page_name.setText("  " + name)

    def setMasteryRank(self, mid, rank):
        self.mastery_rank_labels[mid].setText(rank)
        #self.mastery_rank_labels[str(mid)].setText(rank)

    def setTotalPoints(self):
        ferocity_points = 0
        cunning_points = 0
        resolve_points = 0
        for x in self.mastery_rank_labels.keys():
            if x > 6100 and x < 6200:
                #if int(x) > 4100 and int(x) < 4200:
                ferocity_points += int(self.mastery_rank_labels[x].text())
            elif x > 6200 and x < 6300:
                #elif int(x) > 4200 and int(x) < 4300:
                resolve_points += int(self.mastery_rank_labels[x].text())
            else:
                cunning_points += int(self.mastery_rank_labels[x].text())
        self.total_ferocity_points.setText(str(ferocity_points))
        self.total_cunning_points.setText(str(cunning_points))
        self.total_resolve_points.setText(str(resolve_points))

    def setMasteryLabels(self, ferocityList, cunningList, resolveList):
        self.setMasteryTree(self.ferocity_tree, ferocityList)
        self.setMasteryTree(self.cunning_tree, cunningList)
        self.setMasteryTree(self.resolve_tree, resolveList)

    def setMasteryTree(self, tree, imageList):
        yPos = 3
        xPos = 7
        column = 1
        for element in imageList.keys():
            if not isinstance(element, str):
                mastery = QLabel(tree)
                mastery.setScaledContents(True)
                mastery.move(xPos, yPos)
                mastery.resize(30, 30)
                mastery.setPixmap(imageList[element])

                mastery_rank = QLabel(tree)
                mastery_rank.move(xPos + 31, yPos + 15)
                mastery_rank.resize(15, 15)
                mastery_rank.setAlignment(Qt.AlignCenter)
                mastery_rank.setText('0')
                mastery_rank.setStyleSheet(
                    "QLabel {color:white; border-style: outset; border-width: 2px; border-color: black}"
                )
                self.mastery_rank_labels[element] = mastery_rank
            if column < 3:
                xPos += 56
                column += 1
            else:
                column = 1
                xPos = 7
                yPos += 35
Exemplo n.º 46
0
class MainFrame(QWidget):
        
    def __init__(self,parent = None):
        super(MainFrame,self).__init__(parent)
        
        language = StoreInfoParser.instance().getLanguage()
        m_pTranslator = QTranslator()
        exePath = "./"
        if language == "chinese":
            QmName = "zh_CN.qm"
            StoreInfoParser.instance().setLanguage("chinese")
        else:
            QmName = "en_US.qm"
            
        if(m_pTranslator.load(QmName, exePath)):
            QCoreApplication.instance().installTranslator(m_pTranslator)
        #初始化子控件
        self.initSubWidget()

        #绑定信号和槽
        self.bandSignalSlot()
        
        self.setMinimumSize(800,600)
        self.showFullScreen()
        
        self.updateWidgetInfo()
        self.setPosition()
        #self.repaint()
    def initSubWidget(self):
        
        self.linesPath = None
        self.widthtwo = 0
        self.widthseven = 0
        self.heightone = 0
        self.heightfive = 0
        
        self.copyLabel = QLabel(self)
        self.copyLabel.setFixedWidth(400)
        self.copyLabel.setAlignment(Qt.AlignCenter)
        self.nameLabel = QLabel(self)
        self.nameLabel.setFixedWidth(400)
        self.nameLabel.setAlignment(Qt.AlignCenter)
        self.copyLabel.setFont(QFont("simhei",9))
        self.nameLabel.setFont(QFont("simhei",15))
        
        self.netLabel = QLabel(self)
        self.netLabel.setFixedWidth(800)
        self.netLabel.setFixedHeight(20)
        #self.netLabel.setAlignment(Qt.AlignLeft)
        self.netLabel.setAlignment(Qt.AlignCenter)
        self.netLabel.setText(self.tr("Can not connect to server, please check network and server address!"))
        self.netLabel.setFont(QFont("simhei",12,QFont.Bold))
        pe = QPalette()
        pe.setColor(QPalette.WindowText,Qt.red)
        self.netLabel.setPalette(pe)
        self.netLabel.hide()
        
        #self.updateTimer = QTimer(self)
        #self.connect(self.updateTimer, SIGNAL("timeout"),self.updateWidgetInfo)
        #self.updateTimer.start(10)
        
        #主窗口
        self.mainwindow = MainWindow(self)

        #关于对话框
        self.aboutWidget = AboutWidget(self)
        self.aboutWidget.hide()
        #self.showDlg = SettingWidget(self.mainwindow)
        #日志窗口
        #self.recordWidget = RecordWidget(self)
        #self.recordWidget.mythread.stop()
        #self.recordWidget.hide()

        #self.toolWidget = ToolWidget()
        #self.toolWidget.hide()

        #创建action
        #self.action_showRecord_A = QAction(self)
        #self.action_closeRecord_B = QAction(self)
        #self.action_showRecord_A.setShortcut(QKeySequence(Qt.CTRL + Qt.ALT + Qt.Key_B))
        #self.action_closeRecord_B.setShortcut(QKeySequence(Qt.CTRL + Qt.ALT + Qt.Key_C))
        #self.addAction(self.action_showRecord_A)
        #self.addAction(self.action_closeRecord_B)
        
        self.udpClient = UdpClient()
        self.connect(self.udpClient, SIGNAL("start"),self.startB)
        self.connect(self.udpClient, SIGNAL("stop"),self.stopB)
    
    def initLanguage(self):
        language = StoreInfoParser.instance().getLanguage()
        m_pTranslator = QTranslator()
        exePath = "./"
        if language == "chinese":
            QmName = "zh_CN.qm"
        else:
            QmName = "en_US.qm"
            
        if(m_pTranslator.load(QmName, exePath)):
            QCoreApplication.instance().installTranslator(m_pTranslator)
    
    
    def updateWindow(self,language):
        hintInfo = self.tr("MASSCLOUDS CO.,LTD. Copyright 2014-2018")
        self.copyLabel.setText(hintInfo)
        self.netLabel.setText(self.tr("Can not connect to server, please check network and server address!"))
        self.mainwindow.updateWindow(language)
        #self.recordWidget.updateWindow()
        self.aboutWidget.updateWindow()
        
    def startB(self):
        self.udpClient.show()
        self.setBroadSize()
        
    def setBroadSize(self,width=None,height=None):
        #if self.udpClient.isActiveWindow():
        if width == None:
            widtht = self.getWidth()
            heightt = self.getHeight()
            self.udpClient.setFixedSize(QSize(widtht,heightt))
        else:
            self.udpClient.setFixedSize(QSize(width,height))
        
        self.udpClient.move(QPoint(0,0))
            #self.udpClient.imgLabelTwo.setFixedSize(QSize(QApplication.desktop().width(),QApplication.desktop().height()))
        
    def stopB(self):
        
        self.udpClient.close()

    def bandSignalSlot(self):
        """绑定信号和槽"""
        self.connect(self.mainwindow, SIGNAL("showToolDialog"),self.slotShowToolDialog)
        self.connect(self.mainwindow, SIGNAL("update"),self.slotUpdate)
        self.connect(self.mainwindow, SIGNAL("terminalchange"),self.changeTerminalName)
        self.connect(self.mainwindow, SIGNAL("resetsolution"),self.setPosition)
        self.connect(self.mainwindow, SIGNAL("connectfailed"),self.showNetlabel)
        self.connect(self.mainwindow, SIGNAL("connectsuccess"),self.hideNetlabel)

        #self.connect(self.action_showRecord_A,SIGNAL("triggered()"),self.showRecord)
        #self.connect(self.action_closeRecord_B,SIGNAL("triggered()"),self.closeRecord)

    def showNetlabel(self):
        self.netLabel.show()
        
    def hideNetlabel(self):
        self.netLabel.hide()
        self.udpClient.bindUdpPort()

    def changeTerminalName(self):
        name = globalvariable.TERMINAL_NAME
        self.nameLabel.setText(name)
        self.setPosition()
    
    def showRecord(self):
        self.recordWidget.show()
        self.recordWidget.mythread.start()
        self.recordWidget.move((self.width()-self.recordWidget.width())/2,(self.height()-self.recordWidget.height())/2)
    
    def closeRecord(self):
        self.recordWidget.mythread.stop()
        self.recordWidget.close()
        
        
    def slotShowToolDialog(self, actionType):
        showDlg = None
        if actionType == "showSetting":
            if PasswordDialog().exec_() == QDialog.Accepted:
                showDlg = SettingWidget(self.mainwindow)
                #showDlg.updateWindow()
                showDlg.move(QPoint(self.geometry().width()/9*2,self.geometry().height()/6))
                if self.geometry().width() < 1440:
                    showDlg.resize(QSize(self.geometry().width()/9*5,self.geometry().height()/6*4))
                else:
                    showDlg.resize(QSize(self.geometry().width()/9*5,self.geometry().height()/6*4))
                self.connect(showDlg, SIGNAL("resizePosition"),self.resizePostion)
                self.connect(showDlg, SIGNAL("languagechanged"),self.slotLanguageChange)
                showDlg.exec_()
        elif actionType == "showTerminalTools":
            showDlg = ToolWidget()
            showDlg.move(QPoint(self.geometry().width()/9*2,self.geometry().height()/6))
            showDlg.resize(QSize(self.geometry().width()/9*5,self.geometry().height()/6*4))
            showDlg.exec_()
            #self.toolWidget.show()
            #self.toolWidget.move(QPoint(self.geometry().width()/9*2,self.geometry().height()/6))
            #self.toolWidget.resize(QSize(self.geometry().width()/9*5,self.geometry().height()/6*4))
            
        elif actionType == "showAbout":
            self.aboutWidget.show()
            desktop = QApplication.desktop()
            self.aboutWidget.move((desktop.width() - self.aboutWidget.width())/2, (desktop.height() - self.aboutWidget.height())/2)
#             
    def updateWidgetInfo(self):
        
        self.widthtwo = self.getWidth()/9*2
        self.widthseven = self.getWidth()/9*7
        self.heightone = self.getHeight()/6
        self.heightfive = self.getHeight()/6*5
        
    def updateLinesPath(self):
        """获取四条线路径"""
        self.linesPath = QPainterPath()
        self.linesPath.moveTo(self.widthtwo,self.heightone)
        self.linesPath.lineTo(self.widthseven,self.heightone)
        self.linesPath.moveTo(self.widthtwo,self.heightfive)
        self.linesPath.lineTo(self.widthseven,self.heightfive)
        self.linesPath.moveTo(self.widthtwo,self.heightone)
        self.linesPath.lineTo(self.widthtwo,self.heightfive)
        self.linesPath.moveTo(self.widthseven,self.heightone)
        self.linesPath.lineTo(self.widthseven,self.heightfive)
        self.linesPath.closeSubpath()

    def slotUpdate(self):
        self.setPosition()
        self.setBroadSize()

    def getWidth(self):
        '''desktop = QApplication.desktop()
        width = desktop.width()
        height = desktop.height()'''
        width = "1024"
        resolution = StoreInfoParser.instance().getResolutionValue()
        if resolution == None or resolution == "" or len(resolution.split("x")) != 2:
            width = "1024"
        else:
            width = resolution.split("x")[0]
        return int(width)
    
    def getHeight(self):
        height = "768"
        resolution = StoreInfoParser.instance().getResolutionValue()
        if resolution == None or resolution == "" or len(resolution.split("x")) != 2:
            height = "768"
        else:
            height = resolution.split("x")[1]
        return int(height)
    
    def paintEvent(self,paintEvent):
        """设置背景图片,画线"""
        painter = QPainter(self)
        #设置背景图片
        painter.drawPixmap(self.rect(),QPixmap("images/background.png"))
        #获取四条线路径
        self.updateLinesPath()
        painter.setPen(QPen(QColor(Qt.lightGray),1))
        painter.drawPath(self.linesPath)
#         painter.drawText(QPoint(self.geometry().width()*3/7,self.geometry().height()*21/24), self.tr("乾云启创信息科技有限公司\nCopyright 2014-2018"))
        #painter.drawText(QPoint((self.geometry().width() - infoWidth)*1/2, self.geometry().height()*21/24), hintInfo)
        #painter.drawText(QPoint((self.geometry().width() - infoWidth)*1/2,self.geometry().height()*1/24), globalvariable.TERMINAL_NAME)
    def resizePostion(self, widths, heights):
        #self.setPosition()
        #self.repaint()
        #return
        language = StoreInfoParser.instance().getLanguage()
        m_pTranslator = QTranslator()
        exePath = "./"
        if language == "chinese":
            QmName = "zh_CN.qm"
        else:
            QmName = "en_US.qm"
            
        if(m_pTranslator.load(QmName, exePath)):
            QCoreApplication.instance().installTranslator(m_pTranslator)
            
        width = int(widths)
        height = int(heights)
        self.mainwindow.move(QPoint(width/9*2,height/6))
        self.mainwindow.resize(QSize(width/9*5,height/6*4))
        self.mainwindow.setPosition()
        
        hintInfo = self.tr("MASSCLOUDS CO.,LTD. Copyright 2014-2018")
        self.copyLabel.setText(hintInfo)
        infoWidth = self.copyLabel.width()
        #self.copyLabel.move(QPoint(self.geometry().width()*3/7,self.geometry().height()*21/24))
        self.copyLabel.move(QPoint((width-infoWidth)/2,height*22/24))
        
        if globalvariable.TERMINAL_NAME:
            info = globalvariable.TERMINAL_NAME
            self.nameLabel.setText(info)
            infoWidth = self.nameLabel.width()
            self.nameLabel.move(QPoint((width - infoWidth)*1/2,height*1/24))
            
        netlabelwidth = self.netLabel.width()
        self.netLabel.move(QPoint((width-netlabelwidth)/2,height*21/24))
        #self.netLabel.move(QPoint(width/9*2,height/6 - 20))
        
        self.widthtwo = width/9*2
        self.widthseven = width/9*7
        self.heightone = height/6
        self.heightfive = height/6*5
        
        self.update()
        
        self.setBroadSize(width,height)
    
    def slotLanguageChange(self,language1):
        
        m_pTranslator = QTranslator()
        exePath = "./"
        if language1 == "chinese":
            mainwindow.language = "chinese"
            QmName = "zh_CN.qm"
        else:
            mainwindow.language = "english"
            QmName = "en_US.qm"
            
        if(m_pTranslator.load(QmName, exePath)):
            QCoreApplication.instance().installTranslator(m_pTranslator)
            
        
        
        self.updateWindow(language1)
        
    def getDesktopWidth(self):
        pass
        
    def setPosition(self):
        self.setMainwindowPosition()
        #self.setTerminalNamePosition()
        #self.setTerminalCopyRight()
        self.updateWidgetInfo()
        #self.setBroadSize()
        self.repaint()
    
    def setMainwindowPosition(self):
        #调整主窗口的位置和大小

        width = self.getWidth()
        height = self.getHeight()
        self.mainwindow.move(QPoint(width/9*2,height/6))
        self.mainwindow.resize(QSize(width/9*5,height/6*4))
        self.mainwindow.setPosition()
    
    def setTerminalCopyRight(self):
        #显示公司信息

        language = StoreInfoParser.instance().getLanguage()
        m_pTranslator = QTranslator()
        exePath = "./"
        if language == "chinese":
            QmName = "zh_CN.qm"
        else:
            QmName = "en_US.qm"
            
        if(m_pTranslator.load(QmName, exePath)):
            QCoreApplication.instance().installTranslator(m_pTranslator)
            
        width = self.getWidth()
        height = self.getHeight()
        hintInfo = self.tr("MASSCLOUDS CO.,LTD. Copyright 2014-2018")
        self.copyLabel.setText(hintInfo)
        infoWidth = self.copyLabel.width()
        #self.copyLabel.move(QPoint(self.geometry().width()*3/7,self.geometry().height()*21/24))
        self.copyLabel.move(QPoint((width-infoWidth)/2,height*22/24))
        
    def setTerminalNamePosition(self):
        #显示学生机的名称
        width = self.getWidth()
        height = self.getHeight()
        if globalvariable.TERMINAL_NAME:
            info = globalvariable.TERMINAL_NAME
            self.nameLabel.setText(info)
            infoWidth = self.nameLabel.width()
            self.nameLabel.move(QPoint((width - infoWidth)*1/2,height*1/24))
            
        netlabelwidth = self.netLabel.width()
        self.netLabel.move(QPoint((width-netlabelwidth)/2,height*21/24))
         
    def wheelEvent(self,event):
        """鼠标滚轮滚动事件"""
        self.mainwindow.wheelEvent(event)
Exemplo n.º 47
0
class mainUI(QWidget):

    def __init__(self):
        super(mainUI, self).__init__()
        self.btn_browse = QPushButton('Browse',self)
        self.btn_run = QPushButton('Run',self)
        self.lvd_dd = QComboBox(self)
        self.lvsub_dd = QComboBox(self)
        self.lid_dd = QComboBox(self)
        self.lisub_dd = QComboBox(self)
        self.lvd = QLabel('Vd' ,self)
        self.lvsub = QLabel('Vsub', self)
        self.lid = QLabel('Id', self)
        self.lisub = QLabel('Isub', self)
        self.la_vd = QLabel('Step', self)
        self.ln_vd_step = QLineEdit(self)
        self.initUI()

    def initUI(self):
        self.btn_browse.move(60,20)
        self.btn_browse.clicked.connect(self.showFolderDialog)

        self.btn_run.move(60,220)
        self.btn_run.clicked.connect(self.run)
        self.btn_run.setEnabled(False)

        self.lvd.move(38, 64)
        self.lvd_dd.setEditable(True)
        self.lvd_dd.addItems('none x y'.split())
        self.lvd_dd.move(60, 60)

        self.la_vd.move(150, 64)
        self.ln_vd_step.move(180, 60)
        self.ln_vd_step.resize(50,20)

        self.lvsub.move(38, 104)
        self.lvsub_dd.setEditable(True)
        self.lvsub_dd.addItems('none x y'.split())
        self.lvsub_dd.move(60, 100)

        self.lid.move(38, 144)
        self.lid_dd.setEditable(True)
        self.lid_dd.addItems('none x y'.split())
        self.lid_dd.move(60, 140)

        self.lisub.move(38, 184)
        self.lisub_dd.setEditable(True)
        self.lisub_dd.addItems('none x y'.split())
        self.lisub_dd.move(60, 180)

        # self.btn_save = QPushButton('Save', self)
        # self.btn_save.move(60, 100)
        # self.btn_save.clicked.connect(self.save)
        # self.btn_save.setEnabled(False)

        self.setGeometry(300,300,300,260)
        self.setWindowTitle('SnapBack')
        self.show()

    def showFolderDialog(self):
        global filelist
        index = 0
        basex = 60
        basey = 60
        try:
            filelist = QFileDialog.getOpenFileNames(self,'Select Files')
            self.btn_run.setEnabled(True)
            # print(os.path.dirname(os.path.realpath(filelist[0])))
            os.chdir(os.path.dirname(os.path.realpath(filelist[0])))
            # self.chk = QCheckBox('test',self)
            # self.chk.move(basex, basey)
            # self.chk.toggle()
            # self.show()
            # for item in filelist:
            #     basey = basey + (index + 1) * 40
                # self.addchkbox(item, basex, basey)
            # self.update()
            # print(filelist)
        except:
            print(sys.exc_info()[0])

    # def addchkbox(self, item, basex, basey):
    #     base = os.path.basename(item)
    #     l = os.path.splitext(base)[0]
    #     chk = QCheckBox(l,self)
    #     chk.move(basex, basey)
    #     chk.toggle()
        # print(basex)
        # print(basey)

    def run(self):
        global filelist
        # print(filelist)
        # newlist = list(map(self.xtr_plot,filelist))
        if filelist == []:
            QMessageBox.information(self,'Warning', 'Nothing to plot')
            return
        elif self.ln_vd_step.text() == '':
            QMessageBox.information(self, 'Warning', 'Please input step')
            return
        else:
            l_plot = []
            c_plot = []
            if self.lvd_dd.currentText() != 'none':
                l_plot.append('V3')
                c_plot.append(self.lvd_dd.currentText())
            if self.lid_dd.currentText() != 'none':
                l_plot.append('I3')
                c_plot.append(self.lid_dd.currentText())
            if self.lvsub_dd.currentText() != 'none':
                l_plot.append('V1')
                c_plot.append(self.lvsub_dd.currentText())
            if self.lisub_dd.currentText() != 'none':
                l_plot.append('I1')
                c_plot.append(self.lisub_dd.currentText())
            # print(l_plot)
            plt.ion()
            # fig = plt.figure()
            # ax = fig.add_subplot(111)
            # ax.minorticks_on()
            # ax.set_title("Id Vs Vd")
            # ax.set_xlabel('Vd(V)')
            # ax.set_ylabel('Id(A)')
            # ax.yaxis.set_major_formatter(mtick.FormatStrFormatter('%.2e'))
            # ax.xaxis.set_minor_formatter(mtick.FormatStrFormatter('%.2f'))
            # ax.xaxis.set_minor_locator(mtick.AutoMinorLocator(2))
            # ax.yaxis.set_minor_formatter(mtick.FormatStrFormatter('%.2e'))
            # ax.yaxis.set_minor_locator(mtick.AutoMinorLocator(2))
            #
            # ax.grid(b=True, which='major', color='black', linestyle='-')
            # ax.grid(b=True, which='minor', color='r', linestyle='--')
            # i = 1
            for file in filelist:
                self.xtr_plot(file, l_plot, c_plot)
                # i = i + 1
            # plt.legend()
            # plt.show()
            # print(newlist)
            # self.btn_save.setEnabled(True)
            filelist = []
            return

    def closeEvent(self, QCloseEvent):
        plt.ioff()
        plt.close()
        QApplication.quit()
        sys.exit()

    def xtr_plot(self, item, l_plot, c_plot):
        # print(item)
        data1 = []
        i = 0
        with open(item) as f:
            data = f.read()
        data = data.split('\n')
        # print(data)
        for x in data:
            # if i > 2:
            data1.append(x)
            # i += 1
        i = 0
        while True:
            if '' in data1:
                data1.remove('')
            else:
                break
        del data[:]
        temp = []
        for i in range(0,len(data1)):
            if "NO." in data1[0]:
                temp = data1[0].split('\t')
                del data1[0:2]
                break
            else:
                data1.remove(data1[0])
        x = []
        y = []
        y.append([])
        y.append([])
        for s in l_plot:
            i = temp.index(s)
            # print(i)
            if s == 'V3':
                x = [row.split("\t")[i] for row in data1]
            elif s == 'V1':
                x = [row.split("\t")[i] for row in data1]
            elif s == 'I3':
                y[0] = [row.split("\t")[i] for row in data1]
            elif s == 'I1':
                y[1] = [row.split("\t")[i] for row in data1]
        i = 0

        for s in x:
            s = s.replace("V","")
            s = s.replace(" ","")
            if "f" in s:
                s = s.replace("f","")
                num = float(s)/1000000000000000
            elif "p" in s:
                s = s.replace("p","")
                num = float(s)/1000000000000
            elif "n" in s:
                s = s.replace("n","")
                num = float(s)/1000000000
            elif "u" in s:
                s = s.replace("u","")
                num = float(s)/1000000
            elif "m" in s:
                s = s.replace("m","")
                num = float(s)/1000
            else:
                num = float(s)
            x[i] = num
            i += 1
        # print(x)
        i = 0
        m = 0
        for s in y:
            # print(s)
            if s != []:
                for s1 in s:
                    s1 = s1.replace("A","")
                    s1 = s1.replace(" ","")
                    if "f" in s1:
                        s1 = s1.replace("f","")
                        num = float(s1)/1000000000000000
                    elif "p" in s1:
                        s1 = s1.replace("p","")
                        num = float(s1)/1000000000000
                    elif "n" in s1:
                        s1 = s1.replace("n","")
                        num = float(s1)/1000000000
                    elif "u" in s1:
                        s1 = s1.replace("u","")
                        num = float(s1)/1000000
                    elif "m" in s1:
                        s1 = s1.replace("m","")
                        num = float(s1)/1000
                    else:
                        num = float(s1)
                    y[m][i] = num
                    i += 1
                i = 0
            # print(m)
            # print(y[m])
            m += 1
        i = 0
        m = 0
        base = os.path.basename(item)
        l = os.path.splitext(base)[0]
        l = l.replace('T','')
        w_title = ' '.join(['Vg =', str(int(l)-1),'V'])
        # # print(Vd)
        # # print(Id)
        # print(y[0])
        # print(y[1])
        index = len(x)
        step = int(self.ln_vd_step.text())
        Vsub_step = 100
        cols = 5
        nrows = math.ceil(index/step/5)
        fig, ax = plt.subplots(nrows, cols)
        fig.canvas.set_window_title(w_title)
        ax_row = 0
        ax_col = 0
        max_I = max(y[0])
        if max_I < max(y[1]):
            max_I = max(y[1])
        min_I = min(y[0])
        if min_I > min(y[1]):
            min_I = min(y[0])
        max_V = max(x)
        min_V = min(x)
        Vsub = 0
        while True:
            # ax[ax_row][ax_col] = fig.add_subplot(111)
            # ax[ax_row][ax_col].minorticks_on()
            # ax[ax_row][ax_col].set_title("Id Vs Vd")
            ax[ax_row][ax_col].set_xlabel('Vd(V)')
            ax[ax_row][ax_col].set_ylabel('I(A)')
            ax[ax_row][ax_col].yaxis.set_major_formatter(mtick.FormatStrFormatter('%.2e'))
            # ax[ax_row][ax_col].xaxis.set_minor_formatter(mtick.FormatStrFormatter('%.2f'))
            # ax[ax_row][ax_col].xaxis.set_minor_locator(mtick.AutoMinorLocator(2))
            # ax[ax_row][ax_col].yaxis.set_minor_formatter(mtick.FormatStrFormatter('%.2e'))
            # ax[ax_row][ax_col].yaxis.set_minor_locator(mtick.AutoMinorLocator(2))

            # ax[ax_row][ax_col].grid(b=True, which='major', color='black', linestyle='--')
            # ax[ax_row][ax_col].grid(b=True, which='minor', color='red', linestyle='--')
            m += step
            x_temp = x[i:m]
            ax[ax_row][ax_col].set_autoscale_on(False)
            title = ' '.join(['Vsub=', str(Vsub/1000), 'V'])
            ax[ax_row][ax_col].set_title(title)
            if y[0] != []:
                y_temp = y[0][i:m]
                ax[ax_row][ax_col].plot(x_temp, y_temp, color='red',label='Id')
                # ax[ax_row][ax_col].plot(x_temp, y_temp)
                ax[ax_row][ax_col].set_ylim([min_I*1.1, max_I*1.1])
                ax[ax_row][ax_col].set_xlim([min_V, max_V*1.1])
            if y[1] != []:
                y_temp = y[1][i:m]
                ax[ax_row][ax_col].plot(x_temp, y_temp, color='green',label='Isub')
                # ax[ax_row][ax_col].plot(x_temp, y_temp)
                ax[ax_row][ax_col].set_ylim([min_I*1.1, max_I*1.1])
                ax[ax_row][ax_col].set_xlim([min_V, max_V*1.1])
            # plt.legend()
            ax[ax_row][ax_col].legend(prop={'size':10})
            plt.show()
            i = m
            ax_col += 1
            Vsub += Vsub_step
            if ax_col >= cols:
                ax_col = 0
                ax_row += 1
            if i >= index:
                break
Exemplo n.º 48
0
class Piece(QWidget):

    def __init__(self, type, parent=None):
        super().__init__(parent)
        self.__type = type
        self.setFixedSize(100*variables.SCALE, 91*variables.SCALE)
        self.__section = 7
        self.main_label = QLabel(self)
        self._pixmap = None
        self._selected_pixmap = None
        self.__timer = None
        self.__selected = False
        self.setMouseTracking(True)
        self.__init_main_label()

    def __init_main_label(self):
        if "star_" in self.__type:
            self._pixmap = QPixmap(PATH + os.sep + "assets" + os.sep + "{}.png".format(self.__type[5:]))\
                .scaled(100*variables.SCALE, 91*variables.SCALE, Qt.KeepAspectRatio)
            self._selected_pixmap = QPixmap(PATH + os.sep + "assets" + os.sep +
                                            "{}_selected.png".format(self.__type[5:]))\
                .scaled(100*variables.SCALE, 91*variables.SCALE, Qt.KeepAspectRatio)
            self.__star_label = QLabel(self)
            self.__star_pixmap = QPixmap(PATH + os.sep + "assets" + os.sep + "tiny_star.png")\
                .scaled(variables.STAR_SIZE*variables.SCALE, variables.STAR_SIZE*variables.SCALE, Qt.KeepAspectRatio)
            self.__star_label.setPixmap(self.__star_pixmap)
            self.__star_label.move((50 - variables.STAR_SIZE*variables.SCALE/2)*variables.SCALE,
                                   (46 - variables.STAR_SIZE*variables.SCALE/2)*variables.SCALE)
            self.__star_label.setMouseTracking(True)
        else:
            self._pixmap = QPixmap(PATH + os.sep + "assets" + os.sep + "{}.png".format(self.__type))\
                .scaled(100*variables.SCALE, 91*variables.SCALE, Qt.KeepAspectRatio)
            self._selected_pixmap = QPixmap(PATH + os.sep + "assets" + os.sep + "{}_selected.png".format(self.__type))\
                .scaled(100*variables.SCALE, 91*variables.SCALE, Qt.KeepAspectRatio)
        self.main_label.setPixmap(self._pixmap)
        self.main_label.setMask(self._pixmap.mask())
        self.setMask(self.main_label.mask())
        self.main_label.setFixedSize(100*variables.SCALE, 91*variables.SCALE)
        self.main_label.show()
        self.main_label.setMouseTracking(True)

    @property
    def selected(self):
        return self.__selected

    @selected.setter
    def selected(self, value):
        self.__set_selected(value)

    def __set_selected(self, selected):
        self.__selected = selected
        if selected:
            self.main_label.setPixmap(self._selected_pixmap)
        else:
            self.main_label.setPixmap(self._pixmap)

    def leaveEvent(self, event):
        self.__section = 7

    def mousePressEvent(self, QMouseEvent):
        self.parent().pieceClickedSignal.emit(PieceClickedEvent(self.column, self.row, self.__section, self))
        QMouseEvent.accept()

    def mouseMoveEvent(self, event):
        v1 = event.y() - 45*variables.SCALE
        v2 = event.x() - 46.3*variables.SCALE
        u1 = 45*variables.SCALE
        u2 = 75*variables.SCALE

        numerator = abs(u1*v1 + u2*v2)
        denominator = math.sqrt(u1**2 + u2**2) * math.sqrt(v1**2 + v2**2)
        if denominator != 0:
            angle = math.degrees(math.acos(numerator/denominator))

            if (45/75)*event.x() + 15*variables.SCALE >= event.y():
                if (-75/45)*event.x() + 128.33*variables.SCALE < event.y():
                    angle = 180 - angle
            else:
                if (-75/45)*event.x() + 128.33*variables.SCALE >= event.y():
                    angle = 360 - angle
                else:
                    angle += 180

            if 0 <= angle <= 60:
                self.section_entered(1)
            elif 60 < angle <= 120:
                self.section_entered(2)
            elif 120 < angle <= 180:
                self.section_entered(3)
            elif 180 < angle <= 240:
                self.section_entered(4)
            elif 240 < angle <= 300:
                self.section_entered(5)
            else:
                self.section_entered(6)
        else:
            # Mouse en el centro
            pass

    def section_entered(self, section):
        if self.__section != section:
                self.__section = section
                variables.GAME_INTERFACE.piece_section_entered(section, self)

    def animated_move(self, final_pos, on_move_end=None):
        if variables.ANIMATIONS:
            if self.__timer is None:
                self.__timer = MovePieceTimer(self, final_pos, self.parent(), on_move_end)
                self.__timer.start()
            else:
                if not sip.isdeleted(self.__timer):
                    self.__timer.deleteLater()
                self.__timer = MovePieceTimer(self, final_pos, self.parent(), on_move_end)
                self.__timer.start()
        else:
            self.move(*final_pos)
Exemplo n.º 49
0
class YPipeWidget(QWidget):
    def __init__(self, leftFlow=0, rightFlow=0, maxFlow=100, parent=None):
        super(YPipeWidget, self).__init__(parent)

        self.leftSpinBox = QSpinBox(self)
        self.leftSpinBox.setRange(0, maxFlow)
        self.leftSpinBox.setValue(leftFlow)
        self.leftSpinBox.setSuffix(" l/s")
        self.leftSpinBox.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.connect(self.leftSpinBox, SIGNAL("valueChanged(int)"),
                     self.valueChanged)

        self.rightSpinBox = QSpinBox(self)
        self.rightSpinBox.setRange(0, maxFlow)
        self.rightSpinBox.setValue(rightFlow)
        self.rightSpinBox.setSuffix(" l/s")
        self.rightSpinBox.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.connect(self.rightSpinBox, SIGNAL("valueChanged(int)"),
                     self.valueChanged)

        self.label = QLabel(self)
        self.label.setFrameStyle(QFrame.StyledPanel | QFrame.Sunken)
        self.label.setAlignment(Qt.AlignCenter)
        fm = QFontMetricsF(self.font())
        self.label.setMinimumWidth(fm.width(" 999 l/s "))

        self.setSizePolicy(
            QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))
        self.setMinimumSize(self.minimumSizeHint())
        self.valueChanged()

    def valueChanged(self):
        a = self.leftSpinBox.value()
        b = self.rightSpinBox.value()
        self.label.setText("{0} l/s".format(a + b))
        self.emit(SIGNAL("valueChanged"), a, b)
        self.update()

    def values(self):
        return self.leftSpinBox.value(), self.rightSpinBox.value()

    def minimumSizeHint(self):
        return QSize(self.leftSpinBox.width() * 3,
                     self.leftSpinBox.height() * 5)

    def resizeEvent(self, event=None):
        fm = QFontMetricsF(self.font())
        x = (self.width() - self.label.width()) / 2
        y = self.height() - (fm.height() * 1.5)
        self.label.move(x, y)
        y = self.height() / 60.0
        x = (self.width() / 4.0) - self.leftSpinBox.width()
        self.leftSpinBox.move(x, y)
        x = self.width() - (self.width() / 4.0)
        self.rightSpinBox.move(x, y)

    def paintEvent(self, event=None):
        LogicalSize = 100.0

        def logicalFromPhysical(length, side):
            return (length / side) * LogicalSize

        fm = QFontMetricsF(self.font())
        ymargin = (
            (LogicalSize / 30.0) +
            logicalFromPhysical(self.leftSpinBox.height(), self.height()))
        ymax = (LogicalSize -
                logicalFromPhysical(fm.height() * 2, self.height()))
        width = LogicalSize / 4.0
        cx, cy = LogicalSize / 2.0, LogicalSize / 3.0
        ax, ay = cx - (2 * width), ymargin
        bx, by = cx - width, ay
        dx, dy = cx + width, ay
        ex, ey = cx + (2 * width), ymargin
        fx, fy = cx + (width / 2), cx + (LogicalSize / 24.0)
        gx, gy = fx, ymax
        hx, hy = cx - (width / 2), ymax
        ix, iy = hx, fy

        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        side = min(self.width(), self.height())
        painter.setViewport((self.width() - side) / 2,
                            (self.height() - side) / 2, side, side)
        painter.setWindow(0, 0, LogicalSize, LogicalSize)

        painter.setPen(Qt.NoPen)

        gradient = QLinearGradient(QPointF(0, 0), QPointF(0, 100))
        gradient.setColorAt(0, Qt.white)
        a = self.leftSpinBox.value()
        gradient.setColorAt(1, (Qt.red if a != 0 else Qt.white))
        painter.setBrush(QBrush(gradient))
        painter.drawPolygon(QPolygon([ax, ay, bx, by, cx, cy, ix, iy]))

        gradient = QLinearGradient(QPointF(0, 0), QPointF(0, 100))
        gradient.setColorAt(0, Qt.white)
        b = self.rightSpinBox.value()
        gradient.setColorAt(1, (Qt.blue if b != 0 else Qt.white))
        painter.setBrush(QBrush(gradient))
        painter.drawPolygon(QPolygon([cx, cy, dx, dy, ex, ey, fx, fy]))

        if (a + b) == 0:
            color = QColor(Qt.white)
        else:
            ashare = (a / (a + b)) * 255.0
            bshare = 255.0 - ashare
            color = QColor(ashare, 0, bshare)
        gradient = QLinearGradient(QPointF(0, 0), QPointF(0, 100))
        gradient.setColorAt(0, Qt.white)
        gradient.setColorAt(1, color)
        painter.setBrush(QBrush(gradient))
        painter.drawPolygon(QPolygon([cx, cy, fx, fy, gx, gy, hx, hy, ix, iy]))

        painter.setPen(Qt.black)
        painter.drawPolyline(QPolygon([ax, ay, ix, iy, hx, hy]))
        painter.drawPolyline(QPolygon([gx, gy, fx, fy, ex, ey]))
        painter.drawPolyline(QPolygon([bx, by, cx, cy, dx, dy]))
Exemplo n.º 50
0
class parcial(QWidget):
    def __init__(self):

        self.ingresar = QApplication(sys.argv)
        super(parcial, self).__init__(None)

        self.ingreso = QWidget()
        self.ingreso.resize(440, 320)
        self.ingreso.setWindowTitle('Autenticacion de Ingreso')

        self.sistema = QWidget()
        self.sistema.resize(480, 320)
        self.sistema.setWindowTitle('Identificador de Numeros Telefonicos')

    def inicio(self, u=0, c=0):

        self.imaje = QLabel(self.ingreso)
        self.imaje.setGeometry(10, 10, 225, 225)
        self.imaje.setPixmap(QPixmap(getcwd() + "/logo.gif"))

        self.u = QLabel('Nombre de Usuario:', self.ingreso)
        self.u.move(288, 162)

        self.c = QLabel('Clave:', self.ingreso)
        self.c.move(333, 202)

        self.m = QLabel('Usuario y(o) Clave Incorrecta', self.ingreso)
        self.m.move(250, 303)
        self.m.hide()

        self.User = QLineEdit(self.ingreso)
        self.User.setGeometry(280, 180, 140, 20)

        self.Pass = QLineEdit(self.ingreso)
        self.Pass.setGeometry(280, 220, 140, 20)

        self.entra = QPushButton('Entrar', self.ingreso)
        self.entra.setGeometry(320, 260, 60, 30)

        self.ingreso.connect(self.entra, SIGNAL('clicked()'),
                             lambda: self.revisar(self.User, self.Pass))

        self.ingreso.show()

        sys.exit(self.ingresar.exec_())

    def revisar(self, user, passw, flag=0):

        u = user.text()
        c = passw.text()
        #print u+''+c
        login = open('login.txt', 'rU')
        for i in login:
            if i == u + ',' + c + '\n':
                flag = 1
                self.m.hide()
                m = menu()
                m.exec_()

        if flag == 0:
            self.m.show()

        self.ingreso.update()
        login.close()
Exemplo n.º 51
0
class CImprovedButton(QToolButton):
    def __init__(self, parent=None):
        QToolButton.__init__(self, parent)

        #TESTO ALTERNATIVO
        #Spesso se il pulsante ha icona troppo grossa e quando per ragioni di spazio o altro non si può spostare
        #o ridimensionare il pulsante stesso, la label ha posizioni assurde e schifose. Aggiungerne una "+ controllabile"
        #è l'unico modo..
        self.__fixed_label = QLabel("alternative label", self)
        self.__fixed_label.move(0, self.geometry().height() - 35)
        self.__fixed_label.resize(self.geometry().width(), self.__fixed_label.geometry().height())
        self.__fixed_label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
        self.__font = QtGui.QFont("Arial", 10)
        self.__fixed_label.setFont(self.__font)
        self.__fixed_label.show()

        #INDICATORE STILE iOS
        self.__indicator = QLabel("0", self)
        self.__indicator.setStyleSheet("border-image: url(':/images/backgrounds/indicator.png'); padding-right:1px; color: white;")
        self.__indicator.geometry().setWidth(25)
        self.__indicator.geometry().setHeight(20)
        self.__indicator.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
        self.__indicator.setVisible(False)
        self.setIndicatorPos(QPoint(self.width() - self.__indicator.width(), 0)) #default top-right corner
        #Quando il pulsante viene ridimensionato (designer o meno) devo anche sistemare la label di conseguenza
        self.resizeEvent = self.__onResize
        self.__indicator.resizeEvent = self.__on_indicator_Resize

        self.setToolButtonStyle(QtCore.Qt.ToolButtonIconOnly)

        self.clicked.connect(self.stopAllAnimations)

        #BLINK
        self.__blink_timer = QTimer(parent)
        self.__blink_timer.timeout.connect(self.__on_blink_timer)
        self.__blink_timer_interval = 1000

        #FADING
        self.__opacity_effect = QGraphicsOpacityEffect()
        self.__fading_timer = QTimer(parent)
        self.__fading_timer.timeout.connect(self.__on_fading_timer)
        self.__FADE_TYPE = Enum("IN", "OUT")
        self.__fade_time = 20
        self.__opacity = 1.0
        self.__opacity_fading_coefficient = 0.02
        self.__selected_fade_type = self.__FADE_TYPE.IN

        # ANIMAZIONI GROW
        self.__animationGrow = QPropertyAnimation(self, "iconSize", self)
        self.__animationGrow.setDuration(1000)
        self.__animationGrow.setEasingCurve(QEasingCurve.Linear)
        self.__animationGrow.finished.connect(self.__on_growed)

        self.__animationShrink = QPropertyAnimation(self, "iconSize", self)
        self.__animationShrink.setDuration(1000)
        self.__animationShrink.setEasingCurve(QEasingCurve.Linear)
        self.__animationShrink.finished.connect(self.__on_shrinked)

        self.__defaultIconDimension = 60
        self.__iconGrowsBy = 40
        self.__growing = False

        # ANIMAZIONI BOUNCE
        self.__animationUp = QPropertyAnimation(self, "pos", self)
        self.__animationUp.setDuration(200)
        self.__animationUp.setEasingCurve(QEasingCurve.Linear)
        self.__animationUp.finished.connect(self.__on_top_reached)

        self.__animationBounce = QPropertyAnimation(self, "pos", self)
        self.__animationBounce.setDuration(1000)
        self.__animationBounce.setEasingCurve(QEasingCurve.OutBounce)
        self.__animationBounce.finished.connect(self.__on_bounce_finished)

        self.__bouncing = False
        self.__startPos = QPoint(self.pos().x(), self.pos().y())

        #PIXMAP & MASCHERA
        self.__pmap = QPixmap(self.size())
        self.__pmap_fname = ""
        self.__show_mask_preview = False

    def setDefaultIconSize(self, value):
        """ Sets default icon size when growing stops.
        @param value: size (both width and height)
        @type value: int
        """
        self.__defaultIconDimension = value

    def getDefaultIconSize(self):
        return self.__defaultIconDimension

    defaultIconSize = QtCore.pyqtProperty("int", getDefaultIconSize, setDefaultIconSize)

    def setFixetTextVisibility(self, bool):
        """ Sets if fixed text is visible or not.
        @param bool: visible or not
        @type bool: bool
        """
        self.__fixed_label.setVisible(bool)

    def getFixetTextVisibility(self):
        return self.__fixed_label.isVisible()

    fixetTextVisibility = QtCore.pyqtProperty("bool", fget=getFixetTextVisibility, fset=setFixetTextVisibility)

    def setFixedText(self, txt):
        """ Sets text on the button.
        @param txt: text
        @type txt: string
        """
        self.__fixed_label.setText(txt)

    def getFixedText(self):
        return self.__fixed_label.text()

    fixedText = QtCore.pyqtProperty("QString", getFixedText, setFixedText)

    def setFixedTextPos(self, qpoint):
        """ Sets text position in the button.
        @param qpoint: Position RELATIVE. 0,0 is top left corner of the button.
        @type qpoint: QPoint
        """
        self.__fixed_label.move(qpoint)

    def getFixedTextPos(self):
        return self.__fixed_label.pos()

    fixedTextPos = QtCore.pyqtProperty("QPoint", getFixedTextPos, setFixedTextPos)

    def setFixedTextFont(self, font):
        """ Sets text font.
        @param font: Font for fixed text.
        @type font: QFont
        """
        self.__font = font
        self.__fixed_label.setFont(self.__font)

    def getFixedTextFont(self):
        return self.__font

    fixedTextFont = QtCore.pyqtProperty("QFont", getFixedTextFont, setFixedTextFont)

    #FUNZIONI INDICATORE
    def setIndicatorVisibility(self, bool):
        """ Sets if indicator is visible or not.
        @param bool: visible or not
        @type bool: bool
        """
        self.__indicator.setVisible(bool)

    def getIndicatorVisibility(self):
        return self.__indicator.isVisible()

    indicatorVisibility = QtCore.pyqtProperty("bool", fget=getIndicatorVisibility, fset=setIndicatorVisibility)

    def setIndicatorPos(self, qpoint):
        """ Sets indicator position in the button.
        @param qpoint: Position RELATIVE. 0,0 is top left corner of the button.
        @type qpoint: QPoint
        """
        self.__indicator.move(qpoint)

    def getIndicatorPos(self):
        return self.__indicator.pos()

    indicatorPos = QtCore.pyqtProperty("QPoint", getIndicatorPos, setIndicatorPos)

    def setIndicatorSize(self, size):
        """ Sets indicator size.
        @param size: Size
        @type size: QSize
        """
        self.__indicator.resize(size)

    def getIndicatorSize(self):
        return self.__indicator.size()

    indicatorSize = QtCore.pyqtProperty("QSize", getIndicatorSize, setIndicatorSize)

    def setIndicatorFont(self, font):
        """ Sets indicator text font.
        @param font: Font for indicator text.
        @type font: QFont
        """
        self.__indicator.setFont(font)

    def getIndicatorFont(self):
        return self.__indicator.font()

    indicatorFont = QtCore.pyqtProperty("QFont", getIndicatorFont, setIndicatorFont)


    ## FUNZIONI PER BLINK
    def __on_blink_timer(self):
        self.setVisible(not (self.isVisible()))

    def setBlinking(self, blink):
        """ Sets if the button have to blink or not.
        @param blink: blinking or not
        @type blink: bool
        """
        if blink:
            self.__blink_timer.setInterval(self.__blink_timer_interval)
            self.__blink_timer.start()
        else:
            self.__blink_timer.stop()
            self.setVisible(True)

    def setBlinkInterval(self, value):
        """ Sets blink interval.
        @param blink: blink interval (msec)
        @type blink: int
        """
        self.__blink_timer_interval = value

    def getBlinkInterval(self):
        return self.__blink_timer_interval

    blinkInterval = QtCore.pyqtProperty("int", getBlinkInterval, setBlinkInterval)


    ##FUNZIONI PER FADING
    def fadeIn(self):
        """
         Button fades in from completely invisible to completely visible.
        """
        self.__opacity = 0.0
        self.__selected_fade_type = self.__FADE_TYPE.IN
        self.__fading_timer.start(self.__fade_time)

    def fadeOut(self):
        """
         Button fades out from completely visible to completely invisible.
        """
        self.__selected_fade_type = self.__FADE_TYPE.OUT
        self.__fading_timer.start(self.__fade_time)

    def setFadeTime(self, value):
        """ Sets fading time. Everytime interval is reached, alpha is increased (or decreased) by __opacity_fading_coefficient.
        @param value: fade time (msec)
        @type value: int
        """
        self.__fade_time = value

    def getFadeTime(self):
        return self.__fade_time

    fadeInterval = QtCore.pyqtProperty("int", getFadeTime, setFadeTime)

    def setFadeCoefficient(self, value):
        """ Sets fading coefficient. Alpha is increased (or decreased) by this value.
        @param value: coefficient (min 0.0 - max 1.0)
        @type value: float
        """
        self.__opacity_fading_coefficient = value

    def getFadeCoefficient(self):
        return self.__opacity_fading_coefficient

    fadeCoefficient = QtCore.pyqtProperty("double", getFadeCoefficient, setFadeCoefficient)

    def __on_fading_timer(self):
        if self.__selected_fade_type == self.__FADE_TYPE.OUT:
            if self.__opacity > 0:
                self.__opacity -= self.__opacity_fading_coefficient
                self.__opacity_effect.setOpacity(self.__opacity)
                self.setGraphicsEffect(self.__opacity_effect)
            else:
                self.__fading_timer.stop()

        if self.__selected_fade_type == self.__FADE_TYPE.IN:
            if self.__opacity <= 1.0:
                self.__opacity += self.__opacity_fading_coefficient
                self.__opacity_effect.setOpacity(self.__opacity)
                self.setGraphicsEffect(self.__opacity_effect)
            else:
                self.__fading_timer.stop()

    # FUNZIONI PER GROW\SHRINK
    def __on_growed(self):
        self.__animationShrink.setStartValue(QSize(self.iconSize().width(), self.iconSize().height()))
        self.__animationShrink.setEndValue(
            QSize(self.iconSize().width() - self.__iconGrowsBy, self.iconSize().height() - self.__iconGrowsBy))
        self.__animationShrink.start()

    def __on_shrinked(self):
        self.__animationGrow.setStartValue(QSize(self.iconSize().width(), self.iconSize().height()))
        self.__animationGrow.setEndValue(
            QSize(self.iconSize().width() + self.__iconGrowsBy, self.iconSize().height() + self.__iconGrowsBy))
        self.__animationGrow.start()

    def startGrow(self):
        """
         Button ICON starts to grow and shrink to standard value when maximum size (configured) is reached
        """
        if self.__growing:
            return
        self.__animationGrow.setStartValue(QSize(self.iconSize().width(), self.iconSize().height()))
        self.__animationGrow.setEndValue(
            QSize(self.iconSize().width() + self.__iconGrowsBy, self.iconSize().height() + self.__iconGrowsBy))
        self.__animationGrow.start()
        self.__growing = True

    def stopGrow(self):
        if self.__animationGrow.startValue().toSize() != QSize(0,
                                                               0) and self.__animationShrink.startValue().toSize() != QPoint(
                0, 0):
            self.__animationGrow.stop()
            self.__animationShrink.stop()
            self.setIconSize(QSize(self.__defaultIconDimension, self.__defaultIconDimension))
            self.__growing = False
            
    #FUNZIONI PER BOUNCE
    def startBounce(self):
        """
         Button starts to bounce requiring attention.
        """
        if self.__bouncing:
            return
        self.__startPos = QPoint(self.pos().x(), self.pos().y())
        self.__animationUp.setStartValue(QPoint(self.__startPos.x(), self.__startPos.y()))
        self.__animationUp.setEndValue(QPoint(self.__startPos.x(), self.__startPos.y() - self.geometry().height()))
        self.__animationUp.start()
        self.__bouncing = True
        
    def stopBounce(self):
        if self.__animationUp.startValue().toPoint() != QPoint(0,0) and self.__animationBounce.startValue().toPoint() != QPoint(0,0):
            self.__animationBounce.stop()
            self.__animationUp.stop()
            self.setGeometry(self.__startPos.x(), self.__startPos.y(), self.geometry().width(), self.geometry().height())
            self.__bouncing = False

    def __on_top_reached(self):
        self.__animationBounce.setStartValue(QPoint(self.pos().x(), self.pos().y()))
        self.__animationBounce.setEndValue(QPoint(self.__startPos.x(), self.__startPos.y()))
        self.__animationBounce.start()

    def __on_bounce_finished(self):
        self.__animationUp.start()

    def stopAllAnimations(self):
        self.stopBounce()
        self.stopGrow()

    #FUNZIONI PER PIXMAP & MASCHERA
    def setPixmapFile(self, image_file):
        self.__pmap = image_file
        self.__pmap.scaled(self.size())
        #NB: Il pixmap deve essere BIANCO e NERO. Con heuristicMask il primo pixel in alto a sinistra (0,0) viene
        #usato per decidere il colore trasparente, tutto il resto è visibile.

    def getPixmapFile(self):
        return self.__pmap

    pixmapFile = QtCore.pyqtProperty("QPixmap", getPixmapFile, setPixmapFile)

    def applyMask(self, bool):
        self.__show_mask_preview = bool
        if bool:
            self.setMask(QBitmap(self.__pmap.createHeuristicMask().scaled(self.size())))
        else:
            self.setMask(QBitmap())

    def getMask(self):
        return self.__show_mask_preview

    appliedMask = QtCore.pyqtProperty("bool", fget=getMask, fset=applyMask)

    def __onResize(self, event):
        self.__fixed_label.move(0, self.geometry().height() - 35)
        self.__fixed_label.resize(self.geometry().width(), self.__fixed_label.geometry().height())
        self.setIndicatorPos(QPoint(self.width() - self.__indicator.width(), 0))
        self.__pmap.scaled(self.size())
        if self.__show_mask_preview:
            self.setMask(QBitmap(self.__pmap.createHeuristicMask().scaled(self.size())))

    def __on_indicator_Resize(self, event):
        self.setIndicatorPos(QPoint(self.width() - self.__indicator.width(), 0))
Exemplo n.º 52
0
class parcial(QWidget):

    def __init__(self):
        
        self.ingresar = QApplication(sys.argv)
        super(parcial, self).__init__(None)
        self.contador = 0
        self.ingreso = QWidget()
        self.ingreso.resize(440, 320)
        self.ingreso.setWindowTitle('Autenticacion de Ingreso')
        
        self.sistema = QWidget()
        self.sistema.resize(480, 320)
        self.sistema.setWindowTitle('Identificador de Numeros Telefonicos')

    def inicio(self, u = 0, c = 0):
        
        self.imaje = QLabel(self.ingreso)
        self.imaje.setGeometry(10,10,225,225)
        self.imaje.setPixmap(QPixmap("logo.png"))
        
        self.u = QLabel('Nombre de Usuario:',self.ingreso)
        self.u.move(288,162)
        
        self.c = QLabel('Clave:',self.ingreso)
        self.c.move(333,202)
        
        self.m = QLabel('Usuario y(o) Clave Incorrecta', self.ingreso)
        self.m.move(250,303)
        self.m.hide()
        
        self.User = QLineEdit(self.ingreso)
        self.User.setGeometry(280, 180, 140, 20)
        
        self.Pass = QLineEdit(self.ingreso)
        self.Pass.setGeometry(280, 220, 140, 20)
        key = self.Pass
        key.setEchoMode(self.Pass.Password)
        
        self.entra = QPushButton('Entrar', self.ingreso)
        self.entra.setGeometry(320, 260, 60, 30)
        
        self.ingreso.connect(self.entra, SIGNAL('clicked()'), lambda: self.revisar(self.User, self.Pass))
        
        self.ingreso.show()
        
        sys.exit(self.ingresar.exec_())
        
        
    def revisar(self, user, passw, flag = 0):
        
        u = user.text()
        c = passw.text()
        ce = base64.b64encode(str(c))

        login = open('usuarios.txt', 'rU')
        for i in login:
            n = i.split(',')

            if (n[1] == u and n[4] == ce):
                flag = 1
                self.m.hide()
                m = menu()
                m.exec_()
                break
            elif (n[1] == u and n[4] != ce):
                self.contador += 1
                flag = 0
                self.m.show()
                if self.contador == 3:
                    bloqueado = open('bloqueados.txt', 'a')
                    bloqueado.write(i)
                    bloqueado.close()
        if flag == 0:
            self.m.show()
        
        d = strftime('%d/%m/%y')
        h = strftime('%H:%M:%S')
                            		
        conn = psycopg2.connect(database='test',user='******',password='******', host='localhost')
        cur = conn.cursor()
        cur.execute("INSERT INTO accesos (nombre, usuario, fecha, hora) VALUES ('"+n[0]+"','"+n[1]+"','"+d+"','"+h+"')")
        conn.commit()
        conn.close()

        login.close()
        entrada = open('ingreso.txt', 'a')
        entrada.write('Ha Ingresado '+n[1]+' Hoy '+d+' a las '+h+'\n')
        entrada.close()
Exemplo n.º 53
0
class CImprovedButton(QToolButton):
    def __init__(self, parent=None):
        QToolButton.__init__(self, parent)

        #TESTO ALTERNATIVO
        #Spesso se il pulsante ha icona troppo grossa e quando per ragioni di spazio o altro non si può spostare
        #o ridimensionare il pulsante stesso, la label ha posizioni assurde e schifose. Aggiungerne una "+ controllabile"
        #è l'unico modo..
        self.__fixed_label = QLabel("alternative label", self)
        self.__fixed_label.move(0, self.geometry().height() - 35)
        self.__fixed_label.resize(self.geometry().width(),
                                  self.__fixed_label.geometry().height())
        self.__fixed_label.setAlignment(QtCore.Qt.AlignHCenter
                                        | QtCore.Qt.AlignVCenter)
        self.__font = QtGui.QFont("Arial", 10)
        self.__fixed_label.setFont(self.__font)
        self.__fixed_label.show()

        #INDICATORE STILE iOS
        self.__indicator = QLabel("0", self)
        self.__indicator.setStyleSheet(
            "border-image: url(':/images/backgrounds/indicator.png'); padding-right:1px; color: white;"
        )
        self.__indicator.geometry().setWidth(25)
        self.__indicator.geometry().setHeight(20)
        self.__indicator.setAlignment(QtCore.Qt.AlignHCenter
                                      | QtCore.Qt.AlignVCenter)
        self.__indicator.setVisible(False)
        self.setIndicatorPos(QPoint(self.width() - self.__indicator.width(),
                                    0))  #default top-right corner
        #Quando il pulsante viene ridimensionato (designer o meno) devo anche sistemare la label di conseguenza
        self.resizeEvent = self.__onResize
        self.__indicator.resizeEvent = self.__on_indicator_Resize

        self.setToolButtonStyle(QtCore.Qt.ToolButtonIconOnly)

        self.clicked.connect(self.stopAllAnimations)

        #BLINK
        self.__blink_timer = QTimer(parent)
        self.__blink_timer.timeout.connect(self.__on_blink_timer)
        self.__blink_timer_interval = 1000

        #FADING
        self.__opacity_effect = QGraphicsOpacityEffect()
        self.__fading_timer = QTimer(parent)
        self.__fading_timer.timeout.connect(self.__on_fading_timer)
        self.__FADE_TYPE = Enum("IN", "OUT")
        self.__fade_time = 20
        self.__opacity = 1.0
        self.__opacity_fading_coefficient = 0.02
        self.__selected_fade_type = self.__FADE_TYPE.IN

        # ANIMAZIONI GROW
        self.__animationGrow = QPropertyAnimation(self, "iconSize", self)
        self.__animationGrow.setDuration(1000)
        self.__animationGrow.setEasingCurve(QEasingCurve.Linear)
        self.__animationGrow.finished.connect(self.__on_growed)

        self.__animationShrink = QPropertyAnimation(self, "iconSize", self)
        self.__animationShrink.setDuration(1000)
        self.__animationShrink.setEasingCurve(QEasingCurve.Linear)
        self.__animationShrink.finished.connect(self.__on_shrinked)

        self.__defaultIconDimension = 60
        self.__iconGrowsBy = 40
        self.__growing = False

        # ANIMAZIONI BOUNCE
        self.__animationUp = QPropertyAnimation(self, "pos", self)
        self.__animationUp.setDuration(200)
        self.__animationUp.setEasingCurve(QEasingCurve.Linear)
        self.__animationUp.finished.connect(self.__on_top_reached)

        self.__animationBounce = QPropertyAnimation(self, "pos", self)
        self.__animationBounce.setDuration(1000)
        self.__animationBounce.setEasingCurve(QEasingCurve.OutBounce)
        self.__animationBounce.finished.connect(self.__on_bounce_finished)

        self.__bouncing = False
        self.__startPos = QPoint(self.pos().x(), self.pos().y())

        #PIXMAP & MASCHERA
        self.__pmap = QPixmap(self.size())
        self.__pmap_fname = ""
        self.__show_mask_preview = False

    def setDefaultIconSize(self, value):
        """ Sets default icon size when growing stops.
        @param value: size (both width and height)
        @type value: int
        """
        self.__defaultIconDimension = value

    def getDefaultIconSize(self):
        return self.__defaultIconDimension

    defaultIconSize = QtCore.pyqtProperty("int", getDefaultIconSize,
                                          setDefaultIconSize)

    def setFixetTextVisibility(self, bool):
        """ Sets if fixed text is visible or not.
        @param bool: visible or not
        @type bool: bool
        """
        self.__fixed_label.setVisible(bool)

    def getFixetTextVisibility(self):
        return self.__fixed_label.isVisible()

    fixetTextVisibility = QtCore.pyqtProperty("bool",
                                              fget=getFixetTextVisibility,
                                              fset=setFixetTextVisibility)

    def setFixedText(self, txt):
        """ Sets text on the button.
        @param txt: text
        @type txt: string
        """
        self.__fixed_label.setText(txt)

    def getFixedText(self):
        return self.__fixed_label.text()

    fixedText = QtCore.pyqtProperty("QString", getFixedText, setFixedText)

    def setFixedTextPos(self, qpoint):
        """ Sets text position in the button.
        @param qpoint: Position RELATIVE. 0,0 is top left corner of the button.
        @type qpoint: QPoint
        """
        self.__fixed_label.move(qpoint)

    def getFixedTextPos(self):
        return self.__fixed_label.pos()

    fixedTextPos = QtCore.pyqtProperty("QPoint", getFixedTextPos,
                                       setFixedTextPos)

    def setFixedTextFont(self, font):
        """ Sets text font.
        @param font: Font for fixed text.
        @type font: QFont
        """
        self.__font = font
        self.__fixed_label.setFont(self.__font)

    def getFixedTextFont(self):
        return self.__font

    fixedTextFont = QtCore.pyqtProperty("QFont", getFixedTextFont,
                                        setFixedTextFont)

    #FUNZIONI INDICATORE
    def setIndicatorVisibility(self, bool):
        """ Sets if indicator is visible or not.
        @param bool: visible or not
        @type bool: bool
        """
        self.__indicator.setVisible(bool)

    def getIndicatorVisibility(self):
        return self.__indicator.isVisible()

    indicatorVisibility = QtCore.pyqtProperty("bool",
                                              fget=getIndicatorVisibility,
                                              fset=setIndicatorVisibility)

    def setIndicatorPos(self, qpoint):
        """ Sets indicator position in the button.
        @param qpoint: Position RELATIVE. 0,0 is top left corner of the button.
        @type qpoint: QPoint
        """
        self.__indicator.move(qpoint)

    def getIndicatorPos(self):
        return self.__indicator.pos()

    indicatorPos = QtCore.pyqtProperty("QPoint", getIndicatorPos,
                                       setIndicatorPos)

    def setIndicatorSize(self, size):
        """ Sets indicator size.
        @param size: Size
        @type size: QSize
        """
        self.__indicator.resize(size)

    def getIndicatorSize(self):
        return self.__indicator.size()

    indicatorSize = QtCore.pyqtProperty("QSize", getIndicatorSize,
                                        setIndicatorSize)

    def setIndicatorFont(self, font):
        """ Sets indicator text font.
        @param font: Font for indicator text.
        @type font: QFont
        """
        self.__indicator.setFont(font)

    def getIndicatorFont(self):
        return self.__indicator.font()

    indicatorFont = QtCore.pyqtProperty("QFont", getIndicatorFont,
                                        setIndicatorFont)

    ## FUNZIONI PER BLINK
    def __on_blink_timer(self):
        self.setVisible(not (self.isVisible()))

    def setBlinking(self, blink):
        """ Sets if the button have to blink or not.
        @param blink: blinking or not
        @type blink: bool
        """
        if blink:
            self.__blink_timer.setInterval(self.__blink_timer_interval)
            self.__blink_timer.start()
        else:
            self.__blink_timer.stop()
            self.setVisible(True)

    def setBlinkInterval(self, value):
        """ Sets blink interval.
        @param blink: blink interval (msec)
        @type blink: int
        """
        self.__blink_timer_interval = value

    def getBlinkInterval(self):
        return self.__blink_timer_interval

    blinkInterval = QtCore.pyqtProperty("int", getBlinkInterval,
                                        setBlinkInterval)

    ##FUNZIONI PER FADING
    def fadeIn(self):
        """
         Button fades in from completely invisible to completely visible.
        """
        self.__opacity = 0.0
        self.__selected_fade_type = self.__FADE_TYPE.IN
        self.__fading_timer.start(self.__fade_time)

    def fadeOut(self):
        """
         Button fades out from completely visible to completely invisible.
        """
        self.__selected_fade_type = self.__FADE_TYPE.OUT
        self.__fading_timer.start(self.__fade_time)

    def setFadeTime(self, value):
        """ Sets fading time. Everytime interval is reached, alpha is increased (or decreased) by __opacity_fading_coefficient.
        @param value: fade time (msec)
        @type value: int
        """
        self.__fade_time = value

    def getFadeTime(self):
        return self.__fade_time

    fadeInterval = QtCore.pyqtProperty("int", getFadeTime, setFadeTime)

    def setFadeCoefficient(self, value):
        """ Sets fading coefficient. Alpha is increased (or decreased) by this value.
        @param value: coefficient (min 0.0 - max 1.0)
        @type value: float
        """
        self.__opacity_fading_coefficient = value

    def getFadeCoefficient(self):
        return self.__opacity_fading_coefficient

    fadeCoefficient = QtCore.pyqtProperty("double", getFadeCoefficient,
                                          setFadeCoefficient)

    def __on_fading_timer(self):
        if self.__selected_fade_type == self.__FADE_TYPE.OUT:
            if self.__opacity > 0:
                self.__opacity -= self.__opacity_fading_coefficient
                self.__opacity_effect.setOpacity(self.__opacity)
                self.setGraphicsEffect(self.__opacity_effect)
            else:
                self.__fading_timer.stop()

        if self.__selected_fade_type == self.__FADE_TYPE.IN:
            if self.__opacity <= 1.0:
                self.__opacity += self.__opacity_fading_coefficient
                self.__opacity_effect.setOpacity(self.__opacity)
                self.setGraphicsEffect(self.__opacity_effect)
            else:
                self.__fading_timer.stop()

    # FUNZIONI PER GROW\SHRINK
    def __on_growed(self):
        self.__animationShrink.setStartValue(
            QSize(self.iconSize().width(),
                  self.iconSize().height()))
        self.__animationShrink.setEndValue(
            QSize(self.iconSize().width() - self.__iconGrowsBy,
                  self.iconSize().height() - self.__iconGrowsBy))
        self.__animationShrink.start()

    def __on_shrinked(self):
        self.__animationGrow.setStartValue(
            QSize(self.iconSize().width(),
                  self.iconSize().height()))
        self.__animationGrow.setEndValue(
            QSize(self.iconSize().width() + self.__iconGrowsBy,
                  self.iconSize().height() + self.__iconGrowsBy))
        self.__animationGrow.start()

    def startGrow(self):
        """
         Button ICON starts to grow and shrink to standard value when maximum size (configured) is reached
        """
        if self.__growing:
            return
        self.__animationGrow.setStartValue(
            QSize(self.iconSize().width(),
                  self.iconSize().height()))
        self.__animationGrow.setEndValue(
            QSize(self.iconSize().width() + self.__iconGrowsBy,
                  self.iconSize().height() + self.__iconGrowsBy))
        self.__animationGrow.start()
        self.__growing = True

    def stopGrow(self):
        if self.__animationGrow.startValue().toSize() != QSize(
                0,
                0) and self.__animationShrink.startValue().toSize() != QPoint(
                    0, 0):
            self.__animationGrow.stop()
            self.__animationShrink.stop()
            self.setIconSize(
                QSize(self.__defaultIconDimension,
                      self.__defaultIconDimension))
            self.__growing = False

    #FUNZIONI PER BOUNCE
    def startBounce(self):
        """
         Button starts to bounce requiring attention.
        """
        if self.__bouncing:
            return
        self.__startPos = QPoint(self.pos().x(), self.pos().y())
        self.__animationUp.setStartValue(
            QPoint(self.__startPos.x(), self.__startPos.y()))
        self.__animationUp.setEndValue(
            QPoint(self.__startPos.x(),
                   self.__startPos.y() - self.geometry().height()))
        self.__animationUp.start()
        self.__bouncing = True

    def stopBounce(self):
        if self.__animationUp.startValue().toPoint() != QPoint(
                0,
                0) and self.__animationBounce.startValue().toPoint() != QPoint(
                    0, 0):
            self.__animationBounce.stop()
            self.__animationUp.stop()
            self.setGeometry(self.__startPos.x(), self.__startPos.y(),
                             self.geometry().width(),
                             self.geometry().height())
            self.__bouncing = False

    def __on_top_reached(self):
        self.__animationBounce.setStartValue(
            QPoint(self.pos().x(),
                   self.pos().y()))
        self.__animationBounce.setEndValue(
            QPoint(self.__startPos.x(), self.__startPos.y()))
        self.__animationBounce.start()

    def __on_bounce_finished(self):
        self.__animationUp.start()

    def stopAllAnimations(self):
        self.stopBounce()
        self.stopGrow()

    #FUNZIONI PER PIXMAP & MASCHERA
    def setPixmapFile(self, image_file):
        self.__pmap = image_file
        self.__pmap.scaled(self.size())
        #NB: Il pixmap deve essere BIANCO e NERO. Con heuristicMask il primo pixel in alto a sinistra (0,0) viene
        #usato per decidere il colore trasparente, tutto il resto è visibile.

    def getPixmapFile(self):
        return self.__pmap

    pixmapFile = QtCore.pyqtProperty("QPixmap", getPixmapFile, setPixmapFile)

    def applyMask(self, bool):
        self.__show_mask_preview = bool
        if bool:
            self.setMask(
                QBitmap(self.__pmap.createHeuristicMask().scaled(self.size())))
        else:
            self.setMask(QBitmap())

    def getMask(self):
        return self.__show_mask_preview

    appliedMask = QtCore.pyqtProperty("bool", fget=getMask, fset=applyMask)

    def __onResize(self, event):
        self.__fixed_label.move(0, self.geometry().height() - 35)
        self.__fixed_label.resize(self.geometry().width(),
                                  self.__fixed_label.geometry().height())
        self.setIndicatorPos(QPoint(self.width() - self.__indicator.width(),
                                    0))
        self.__pmap.scaled(self.size())
        if self.__show_mask_preview:
            self.setMask(
                QBitmap(self.__pmap.createHeuristicMask().scaled(self.size())))

    def __on_indicator_Resize(self, event):
        self.setIndicatorPos(QPoint(self.width() - self.__indicator.width(),
                                    0))
Exemplo n.º 54
0
class nuevousuario(QDialog):

    def __init__(self):

        super(nuevousuario, self).__init__(None)
        self.foto = ''
        self.resize(400, 460)
        self.setWindowTitle('Datos de Usuario')
        
        self.imaje = QLabel(self)
        self.imaje.setGeometry(160,210,225,225)
        self.imaje.setPixmap(QPixmap("usuario.png"))
        
        self.n = QLabel('Nombre Completo:',self)
        self.n.move(10,10)
        
        self.u = QLabel('Nombre de Usuario:',self)
        self.u.move(10,50)
        
        self.failu = QLabel('Este Usuario ya Existe',self)
        self.failu.move(140,70)
        self.failu.hide()
        
        self.c = QLabel('Correo Electronico:',self)
        self.c.move(10,90)
        
        self.a = QLabel('Edad:',self)
        self.a.move(10,130)
  
        self.faila = QLabel('Ingrese una Edad',self)
        self.faila.move(140,150)
        self.faila.hide()
      
        self.p = QLabel('Clave:',self)
        self.p.move(10,170)
        
        self.failp = QLabel('Clave muy Debil',self)
        self.failp.move(140,190)
        self.failp.hide()

        self.f = QLabel('Foto:',self)
        self.f.move(10,210)
        
        self.Name = QLineEdit(self)
        self.Name.setGeometry(140, 10, 200, 20)
        
        self.User = QLineEdit(self)
        self.User.setGeometry(140, 50, 200, 20)
        
        self.Mail = QLineEdit(self)
        self.Mail.setGeometry(140, 90, 200, 20)
        
        self.Age = QLineEdit(self)
        self.Age.setGeometry(140, 130, 200, 20)
        
        self.Pass = QLineEdit(self)
        self.Pass.setGeometry(140, 170, 200, 20)

        key = self.Pass
        key.setEchoMode(self.Pass.Password)
        
        self.buscarfoto = QPushButton('Buscar Foto', self)
        self.buscarfoto.setGeometry(10, 250, 100, 30)
        
        self.guardar = QPushButton('Guardar', self)
        self.guardar.setGeometry(30, 300, 60, 30)

        self.failc = QLabel('Llenar Campos Vacios',self)
        self.failc.move(10,350)
        self.failc.hide()

        self.failf = QLabel('Elija Una Foto',self)
        self.failf.move(140,440)
        self.failf.hide()
                
        self.connect(self.buscarfoto, SIGNAL('clicked()'), lambda: self.buscar(self.ponfoto))
        self.connect(self.guardar, SIGNAL('clicked()'), lambda: self.nuevo(self.Name, self.User, self.Mail, self.Age, self.Pass))
        #sys.exit(self.editar.exec_())

    def buscar(self, do):
        e = explorador(do)
        e.exec_()		

    def ponfoto(self, a):
        self.foto = a		
        self.imaje.setPixmap(QPixmap(a))
        #self.show()
        		
    def nuevo(self, name, user, mail, age, passw, pe = 0):
        n = name.text()
        u = user.text()
        m = mail.text()
        a = age.text()
        p = passw.text()
        flag = 0
        if (n != '' and u != '' and m != '' and a != '' and p != ''): #revisa que todos los campos esten llenos
            login = open('login.txt', 'r')
            self.failc.hide()
            
            for i in login:
                if str(u) in i:# revisa si ya existe este nombre de usuario
                    self.failu.show()
                    flag = 0

                else:
                    self.failu.hide()
                    flag = 1

            login.close()
            
            if flag == 1:
                try:# revisa si se ingresa un numero
                    int(a)
                    self.faila.hide()
                    o = self.passcheck(str(p))
                    if o == 1:
                        self.failp.hide()
                        pe = base64.b64encode(str(p))
                        #if self.foto != '':

                        guarda.guardar(n,u,m,a,pe)
                                                        
                        conn = psycopg2.connect(database='test',user='******',password='******', host='localhost')
                        cur = conn.cursor()
                        cur.execute("INSERT INTO usuarios (nombre, usuario, correo, edad, clave) VALUES ('"+n+"','"+u+"','"+m+"','"+a+"','"+pe+"');")
                        conn.commit()
                        conn.close()

                        usuarios = open('usuarios.txt','a')
                        usuarios.write(n+','+u+','+m+','+a+','+pe+','+self.foto+',\n')
                        usuarios.close()
                        self.failf.hide()
                        #break
                        #else:
                        #    self.failf.show()
                    else:
                        self.failp.show() 							
                except ValueError:
                    self.faila.show()


        else:
            self.failc.show()
        
    def passcheck(self, clave, f1 = 0, f2 = 0, f3 = 0, f4 = 0, f5 = 0, minimo = 6, flag = 0):
        for i in clave:
            n = ord(i)
            if (n >= 0 and n < 48): #simbolos
                f1 = 1
            elif (n >= 48 and n < 58): #numeros
                f2 = 1
            elif (n >= 58 and n < 65): #simbolos
                f1 = 1
            elif (n >= 65 and n < 91): #mayusculas
                f3 = 1
            elif (n >= 91 and n < 97): #simbolos
                f1 = 1
            elif (n >= 97 and n < 123): #minus
                f4 = 1
            elif (n == 209):
                f3 = 1
            elif (n == 241):
                f4 = 1
            elif (n >= 123 and n < 256): #simbolos
                f1 = 1

        if len(clave) >= minimo:
            f5 = 1

        if (f1*f2*f3*f4*f5 == 1):
            flag = 1
        else:
            flag = 0
        return flag