示例#1
0
class AdvancedSort(QWidget):
    def __init__(self):
        super(AdvancedSort, self).__init__()
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.ui.sortButton.clicked.connect(self.sortArray)

    @Slot()
    def sortArray(self):
        def toArray(inputStr):
            return [int(item) for item in inputStr.split()]

        def toOutputFormat(arrInfo):
            arr = arrInfo[0]
            time = arrInfo[1]
            return (''.join([str(item) + ' ' for item in arr]) +
                    " (run time = {} sec.)".format(time))

        try:
            arr = toArray(self.ui.inputArray.text())
            assert arr
        except:
            msg = QMessageBox()
            msg.setText("INVALID INPUT")
            msg.exec()
        else:
            self.ui.sortedArrayCocktail.setText(
                toOutputFormat(AdvancedSortCore.cocktailSortWithInfo(arr)))
            self.ui.sortedArrayQuick.setText(
                toOutputFormat(AdvancedSortCore.qSortWithInfo(arr)))
示例#2
0
class Sort(QWidget):
    def __init__(self):
        super(Sort, self).__init__()
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.ui.sortButton.clicked.connect(self.sortArray)

    @Slot()
    def sortArray(self):
        def toArray(inputStr): return [int(item) for item in inputStr.split()]

        def toOutputFormat(arrInfo):
            arr = arrInfo[0]
            comparisons = arrInfo[1]
            changes = arrInfo[2]
            time = arrInfo[3]
            return (''.join([str(item) + ' ' for item in arr]) + 
                    " (number of changes = {}; number of comparisons = {}; run time = {} sec.)".format(comparisons,
                                                                                                       changes, time))

        try:
            arr = toArray(self.ui.inputArray.text())
            assert arr
        except:
            msg = QMessageBox()
            msg.setText("INVALID INPUT")
            msg.exec()
        else:
            self.ui.sortedArrayInsert.setText(toOutputFormat(SortCore.insertSort(arr)))
            self.ui.sortedArraySelect.setText(toOutputFormat(SortCore.selectSort(arr)))
示例#3
0
class Form(QMainWindow):
    finished = pyqtSignal()
    updateProgress = pyqtSignal(int)

    def __init__(self, parent=None):
        super(Form, self).__init__(parent)

        # Install the custom output stream
        sys.stdout = EmittingStream(textWritten=self.normalOutputWritten)

        self.ui = Ui_Form()
        self.ui.setupUi(self)

        self.ui.pushButton_run.clicked.connect(self.start_task)
        self.finished.connect(self.end_task)
        self.updateProgress.connect(self.ui.progressBar.setValue)

    def start_task(self):

        self.thread = threading.Thread(target=self.run_test)
        self.thread.start()
        self.ui.pushButton_run.setEnabled(False)

    def end_task(self):
        self.ui.pushButton_run.setEnabled(True)

    def __del__(self):
        # Restore sys.stdout
        sys.stdout = sys.__stdout__

    def normalOutputWritten(self, text):
        """Append text to the QTextEdit."""
        cursor = self.ui.textEdit.textCursor()
        cursor.movePosition(QTextCursor.End)
        cursor.insertText(text)
        self.ui.textEdit.setTextCursor(cursor)
        self.ui.textEdit.ensureCursorVisible()

    def run_test(self):
        for i in range(100):
            per = i + 1
            self.updateProgress.emit(per)
            # self.ui.progressBar.setValue(per)
            print("%%%s" % per)
            time.sleep(0.15)  # simulating expensive task

        print("Task Completed!")
        time.sleep(1.5)
        self.ui.progressBar.reset()
        self.finished.emit()
示例#4
0
class QmyWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.Lab = 'my new lab'
        # self.ui.LabHello.setText(self.Lab)
        self.ui.label.setText(self.Lab)
        self.ui.pushButton.clicked.connect(self.clicked)

    def setBtnText(self, aText):
        self.ui.label.setText(aText)

    def clicked(self):
        self.ui.label.setText(self.get_now_date())

    @staticmethod
    def get_now_date():
        return str(datetime.datetime.now())
示例#5
0
class RSA(QWidget):
    def __init__(self):
        super(RSA, self).__init__()
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.ui.generateKeysButton.clicked.connect(self.generateKeysSignal)
        self.ui.encryptButton.clicked.connect(self.encryptSignal)
        self.ui.decryptButton.clicked.connect(self.decryptSignal)

    @Slot()
    def generateKeysSignal(self):
        self.publicKey, self.privateKey = RSACore.generateKeys(N_LENGTH)
        self.publicKey = str(self.publicKey[0]), str(self.publicKey[1])
        self.privateKey = str(self.privateKey[0]), str(self.privateKey[1])
        ciphertext = RSACore.encrypt("test", self.publicKey)
        plaintext = RSACore.decrypt(ciphertext, self.privateKey)
        while not plaintext == "test":
            self.publicKey, self.privateKey = RSACore.generateKeys(N_LENGTH)
            self.publicKey = str(self.publicKey[0]), str(self.publicKey[1])
            self.privateKey = str(self.privateKey[0]), str(self.privateKey[1])
            ciphertext = RSACore.encrypt("test", self.publicKey)
            plaintext = RSACore.decrypt(ciphertext, self.privateKey)
        self.ui.publicKeywordS.setText(self.publicKey[0])
        self.ui.publicKeywordN.setText(self.publicKey[1])
        self.ui.privateKeywordE.setText(self.privateKey[0])

    @Slot()
    def encryptSignal(self):
        plaintext = self.ui.plaintextEncrypt.toPlainText()
        publicKey = self.ui.publicKeywordS.text(), self.ui.publicKeywordN.text()
        ciphertext = RSACore.encrypt(plaintext, publicKey)
        self.ui.ciphertextEncrypt.setPlainText(ciphertext)
        self.ui.ciphertextDecrypt.setPlainText(ciphertext)

    @Slot()
    def decryptSignal(self):
        ciphertext = self.ui.ciphertextDecrypt.toPlainText()
        privateKey = self.ui.privateKeywordE.text(), self.ui.publicKeywordN.text()
        plaintext = RSACore.decrypt(ciphertext, privateKey)
        self.ui.plaintextDecrypt.setPlainText(plaintext)
示例#6
0
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        self.m_iconSize = QtCore.QSize(64, 64)
        self.m_scene = QtWidgets.QGraphicsScene()

        m_ui = Ui_Form()
        m_ui.setupUi(self)
        m_ui.easingCurvePicker.setIconSize(self.m_iconSize)
        m_ui.easingCurvePicker.setMinimumHeight(self.m_iconSize.height() + 50)
        m_ui.buttonGroup.setId(m_ui.lineRadio, 0)
        m_ui.buttonGroup.setId(m_ui.circleRadio, 1)

        dummy = QtCore.QEasingCurve()
        m_ui.periodSpinBox.setValue(dummy.period())
        m_ui.amplitudeSpinBox.setValue(dummy.amplitude())
        m_ui.overshootSpinBox.setValue(dummy.overshoot())

        m_ui.easingCurvePicker.currentRowChanged.connect(self.curveChanged)
        m_ui.buttonGroup.buttonClicked[int].connect(self.pathChanged)
        m_ui.periodSpinBox.valueChanged.connect(self.periodChanged)
        m_ui.amplitudeSpinBox.valueChanged.connect(self.amplitudeChanged)
        m_ui.overshootSpinBox.valueChanged.connect(self.overshootChanged)

        self.m_ui = m_ui
        self.createCurveIcons()

        pix = QtGui.QPixmap(':/images/qt-logo.png')
        self.m_item = Pixmap(pix)
        self.m_scene.addItem(self.m_item.pixmap_item)
        self.m_ui.graphicsView.setScene(self.m_scene)

        self.m_anim = Animation(self.m_item, 'pos')
        self.m_anim.setEasingCurve(QtCore.QEasingCurve.OutBounce)
        self.m_ui.easingCurvePicker.setCurrentRow(
            int(QtCore.QEasingCurve.OutBounce))

        self.startAnimation()
示例#7
0
   def __init__(self, parent=None):
       super(Window, self).__init__(parent)
 
       self.m_iconSize = QtCore.QSize(64, 64)
       self.m_scene = QtGui.QGraphicsScene()
 
       m_ui = Ui_Form()
       m_ui.setupUi(self)
       m_ui.easingCurvePicker.setIconSize(self.m_iconSize)
       m_ui.easingCurvePicker.setMinimumHeight(self.m_iconSize.height() + 50)
       m_ui.buttonGroup.setId(m_ui.lineRadio, 0)
       m_ui.buttonGroup.setId(m_ui.circleRadio, 1)
 
       dummy = QtCore.QEasingCurve()
       m_ui.periodSpinBox.setValue(dummy.period())
       m_ui.amplitudeSpinBox.setValue(dummy.amplitude())
       m_ui.overshootSpinBox.setValue(dummy.overshoot())
 
       m_ui.easingCurvePicker.currentRowChanged.connect(self.curveChanged)
       m_ui.buttonGroup.buttonClicked[int].connect(self.pathChanged)
       m_ui.periodSpinBox.valueChanged.connect(self.periodChanged)
       m_ui.amplitudeSpinBox.valueChanged.connect(self.amplitudeChanged)
       m_ui.overshootSpinBox.valueChanged.connect(self.overshootChanged)
 
       self.m_ui = m_ui
       self.createCurveIcons()
 
       pix = QtGui.QPixmap(':/images/qt-logo.png')
       self.m_item = Pixmap(pix)
       self.m_scene.addItem(self.m_item.pixmap_item)
       self.m_ui.graphicsView.setScene(self.m_scene)
 
       self.m_anim = Animation(self.m_item, 'pos')
       self.m_anim.setEasingCurve(QtCore.QEasingCurve.OutBounce)
       self.m_ui.easingCurvePicker.setCurrentRow(int(QtCore.QEasingCurve.OutBounce))        
 
       self.startAnimation()
示例#8
0
文件: easing.py 项目: AlexDoul/PyQt4
class Window(QtGui.QWidget):
    def __init__(self, parent=None):
        super(QtGui.QWidget, self).__init__(parent)

        self.m_iconSize = QtCore.QSize(64, 64)
        self.m_scene = QtGui.QGraphicsScene()
        self.m_ui = Ui_Form()

        self.m_ui.setupUi(self)
        self.m_ui.easingCurvePicker.setIconSize(self.m_iconSize)
        self.m_ui.easingCurvePicker.setMinimumHeight(self.m_iconSize.height() + 50)
        self.m_ui.buttonGroup.setId(self.m_ui.lineRadio, 0)
        self.m_ui.buttonGroup.setId(self.m_ui.circleRadio, 1)

        dummy = QtCore.QEasingCurve()
        self.m_ui.periodSpinBox.setValue(dummy.period())
        self.m_ui.amplitudeSpinBox.setValue(dummy.amplitude())
        self.m_ui.overshootSpinBox.setValue(dummy.overshoot())

        self.m_ui.easingCurvePicker.currentRowChanged.connect(self.curveChanged)
        self.m_ui.buttonGroup.buttonClicked[int].connect(self.pathChanged)
        self.m_ui.periodSpinBox.valueChanged.connect(self.periodChanged)
        self.m_ui.amplitudeSpinBox.valueChanged.connect(self.amplitudeChanged)
        self.m_ui.overshootSpinBox.valueChanged.connect(self.overshootChanged)
        self.createCurveIcons()

        pix = QtGui.QPixmap(':/images/qt-logo.png')
        self.m_item = PixmapItem(pix)
        self.m_scene.addItem(self.m_item.pixmap_item)
        self.m_ui.graphicsView.setScene(self.m_scene)

        self.m_anim = Animation(self.m_item, 'pos')
        self.m_anim.setEasingCurve(QtCore.QEasingCurve.OutBounce)
        self.m_ui.easingCurvePicker.setCurrentRow(int(QtCore.QEasingCurve.OutBounce))

        self.startAnimation()

    def createCurveIcons(self):
        pix = QtGui.QPixmap(self.m_iconSize)
        painter = QtGui.QPainter()

        gradient = QtGui.QLinearGradient(0, 0, 0, self.m_iconSize.height())
        gradient.setColorAt(0.0, QtGui.QColor(240, 240, 240))
        gradient.setColorAt(1.0, QtGui.QColor(224, 224, 224))

        brush = QtGui.QBrush(gradient)

        # The original C++ code uses undocumented calls to get the names of the
        # different curve types.  We do the Python equivalant (but without
        # cheating).
        curve_types = [(n, c) for n, c in QtCore.QEasingCurve.__dict__.items()
                if isinstance(c, QtCore.QEasingCurve.Type) and c != QtCore.QEasingCurve.Custom]
        curve_types.sort(key=lambda ct: ct[1])

        painter.begin(pix)

        for curve_name, curve_type in curve_types:
            painter.fillRect(
                    QtCore.QRect(QtCore.QPoint(0, 0), self.m_iconSize), brush)

            curve = QtCore.QEasingCurve(curve_type)

            painter.setPen(QtGui.QColor(0, 0, 255, 64))
            xAxis = self.m_iconSize.height() / 1.5
            yAxis = self.m_iconSize.width() / 3.0
            painter.drawLine(0, xAxis, self.m_iconSize.width(),  xAxis)
            painter.drawLine(yAxis, 0, yAxis, self.m_iconSize.height())

            curveScale = self.m_iconSize.height() / 2.0;

            painter.setPen(QtCore.Qt.NoPen)

            # Start point.
            painter.setBrush(QtCore.Qt.red)
            start = QtCore.QPoint(yAxis,
                    xAxis - curveScale * curve.valueForProgress(0))
            painter.drawRect(start.x() - 1, start.y() - 1, 3, 3)

            # End point.
            painter.setBrush(QtCore.Qt.blue)
            end = QtCore.QPoint(yAxis + curveScale,
                    xAxis - curveScale * curve.valueForProgress(1))
            painter.drawRect(end.x() - 1, end.y() - 1, 3, 3)

            curvePath = QtGui.QPainterPath()
            curvePath.moveTo(QtCore.QPointF(start))
            t = 0.0
            while t <= 1.0:
                to = QtCore.QPointF(yAxis + curveScale * t,
                        xAxis - curveScale * curve.valueForProgress(t))
                curvePath.lineTo(to)
                t += 1.0 / curveScale

            painter.setRenderHint(QtGui.QPainter.Antialiasing, True)
            painter.strokePath(curvePath, QtGui.QColor(32, 32, 32))
            painter.setRenderHint(QtGui.QPainter.Antialiasing, False)

            item = QtGui.QListWidgetItem()
            item.setIcon(QtGui.QIcon(pix))
            item.setText(curve_name)
            self.m_ui.easingCurvePicker.addItem(item)

        painter.end()

    def startAnimation(self):
        self.m_anim.setStartValue(QtCore.QPointF(0, 0))
        self.m_anim.setEndValue(QtCore.QPointF(100, 100))
        self.m_anim.setDuration(2000)
        self.m_anim.setLoopCount(-1)
        self.m_anim.start()

    def curveChanged(self, row):
        curveType = QtCore.QEasingCurve.Type(row)
        self.m_anim.setEasingCurve(curveType)
        self.m_anim.setCurrentTime(0)

        isElastic = (curveType >= QtCore.QEasingCurve.InElastic and curveType <= QtCore.QEasingCurve.OutInElastic)
        isBounce = (curveType >= QtCore.QEasingCurve.InBounce and curveType <= QtCore.QEasingCurve.OutInBounce)

        self.m_ui.periodSpinBox.setEnabled(isElastic)
        self.m_ui.amplitudeSpinBox.setEnabled(isElastic or isBounce)
        self.m_ui.overshootSpinBox.setEnabled(curveType >= QtCore.QEasingCurve.InBack and curveType <= QtCore.QEasingCurve.OutInBack)

    def pathChanged(self, index):
        self.m_anim.setPathType(index)

    def periodChanged(self, value):
        curve = self.m_anim.easingCurve()
        curve.setPeriod(value)
        self.m_anim.setEasingCurve(curve)

    def amplitudeChanged(self, value):
        curve = self.m_anim.easingCurve()
        curve.setAmplitude(value)
        self.m_anim.setEasingCurve(curve)

    def overshootChanged(self, value):
        curve = self.m_anim.easingCurve()
        curve.setOvershoot(value)
        self.m_anim.setEasingCurve(curve)
示例#9
0
class Window(QtGui.QWidget):
    def __init__(self, parent=None):
        super(QtGui.QWidget, self).__init__(parent)

        self.m_iconSize = QtCore.QSize(64, 64)
        self.m_scene = QtGui.QGraphicsScene()
        self.m_ui = Ui_Form()

        self.m_ui.setupUi(self)
        self.m_ui.easingCurvePicker.setIconSize(self.m_iconSize)
        self.m_ui.easingCurvePicker.setMinimumHeight(self.m_iconSize.height() +
                                                     50)
        self.m_ui.buttonGroup.setId(self.m_ui.lineRadio, 0)
        self.m_ui.buttonGroup.setId(self.m_ui.circleRadio, 1)

        dummy = QtCore.QEasingCurve()
        self.m_ui.periodSpinBox.setValue(dummy.period())
        self.m_ui.amplitudeSpinBox.setValue(dummy.amplitude())
        self.m_ui.overshootSpinBox.setValue(dummy.overshoot())

        self.m_ui.easingCurvePicker.currentRowChanged.connect(
            self.curveChanged)
        self.m_ui.buttonGroup.buttonClicked[int].connect(self.pathChanged)
        self.m_ui.periodSpinBox.valueChanged.connect(self.periodChanged)
        self.m_ui.amplitudeSpinBox.valueChanged.connect(self.amplitudeChanged)
        self.m_ui.overshootSpinBox.valueChanged.connect(self.overshootChanged)
        self.createCurveIcons()

        pix = QtGui.QPixmap(':/images/qt-logo.png')
        self.m_item = PixmapItem(pix)
        self.m_scene.addItem(self.m_item.pixmap_item)
        self.m_ui.graphicsView.setScene(self.m_scene)

        self.m_anim = Animation(self.m_item, 'pos')
        self.m_anim.setEasingCurve(QtCore.QEasingCurve.OutBounce)
        self.m_ui.easingCurvePicker.setCurrentRow(
            int(QtCore.QEasingCurve.OutBounce))

        self.startAnimation()

    def createCurveIcons(self):
        pix = QtGui.QPixmap(self.m_iconSize)
        painter = QtGui.QPainter()

        gradient = QtGui.QLinearGradient(0, 0, 0, self.m_iconSize.height())
        gradient.setColorAt(0.0, QtGui.QColor(240, 240, 240))
        gradient.setColorAt(1.0, QtGui.QColor(224, 224, 224))

        brush = QtGui.QBrush(gradient)

        # The original C++ code uses undocumented calls to get the names of the
        # different curve types.  We do the Python equivalant (but without
        # cheating).
        curve_types = [(n, c) for n, c in QtCore.QEasingCurve.__dict__.items()
                       if isinstance(c, QtCore.QEasingCurve.Type)
                       and c != QtCore.QEasingCurve.Custom]
        curve_types.sort(key=lambda ct: ct[1])

        painter.begin(pix)

        for curve_name, curve_type in curve_types:
            painter.fillRect(
                QtCore.QRect(QtCore.QPoint(0, 0), self.m_iconSize), brush)

            curve = QtCore.QEasingCurve(curve_type)

            painter.setPen(QtGui.QColor(0, 0, 255, 64))
            xAxis = self.m_iconSize.height() / 1.5
            yAxis = self.m_iconSize.width() / 3.0
            painter.drawLine(0, xAxis, self.m_iconSize.width(), xAxis)
            painter.drawLine(yAxis, 0, yAxis, self.m_iconSize.height())

            curveScale = self.m_iconSize.height() / 2.0

            painter.setPen(QtCore.Qt.NoPen)

            # Start point.
            painter.setBrush(QtCore.Qt.red)
            start = QtCore.QPoint(
                yAxis, xAxis - curveScale * curve.valueForProgress(0))
            painter.drawRect(start.x() - 1, start.y() - 1, 3, 3)

            # End point.
            painter.setBrush(QtCore.Qt.blue)
            end = QtCore.QPoint(yAxis + curveScale,
                                xAxis - curveScale * curve.valueForProgress(1))
            painter.drawRect(end.x() - 1, end.y() - 1, 3, 3)

            curvePath = QtGui.QPainterPath()
            curvePath.moveTo(QtCore.QPointF(start))
            t = 0.0
            while t <= 1.0:
                to = QtCore.QPointF(
                    yAxis + curveScale * t,
                    xAxis - curveScale * curve.valueForProgress(t))
                curvePath.lineTo(to)
                t += 1.0 / curveScale

            painter.setRenderHint(QtGui.QPainter.Antialiasing, True)
            painter.strokePath(curvePath, QtGui.QColor(32, 32, 32))
            painter.setRenderHint(QtGui.QPainter.Antialiasing, False)

            item = QtGui.QListWidgetItem()
            item.setIcon(QtGui.QIcon(pix))
            item.setText(curve_name)
            self.m_ui.easingCurvePicker.addItem(item)

        painter.end()

    def startAnimation(self):
        self.m_anim.setStartValue(QtCore.QPointF(0, 0))
        self.m_anim.setEndValue(QtCore.QPointF(100, 100))
        self.m_anim.setDuration(2000)
        self.m_anim.setLoopCount(-1)
        self.m_anim.start()

    def curveChanged(self, row):
        curveType = QtCore.QEasingCurve.Type(row)
        self.m_anim.setEasingCurve(curveType)
        self.m_anim.setCurrentTime(0)

        isElastic = (curveType >= QtCore.QEasingCurve.InElastic
                     and curveType <= QtCore.QEasingCurve.OutInElastic)
        isBounce = (curveType >= QtCore.QEasingCurve.InBounce
                    and curveType <= QtCore.QEasingCurve.OutInBounce)

        self.m_ui.periodSpinBox.setEnabled(isElastic)
        self.m_ui.amplitudeSpinBox.setEnabled(isElastic or isBounce)
        self.m_ui.overshootSpinBox.setEnabled(
            curveType >= QtCore.QEasingCurve.InBack
            and curveType <= QtCore.QEasingCurve.OutInBack)

    def pathChanged(self, index):
        self.m_anim.setPathType(index)

    def periodChanged(self, value):
        curve = self.m_anim.easingCurve()
        curve.setPeriod(value)
        self.m_anim.setEasingCurve(curve)

    def amplitudeChanged(self, value):
        curve = self.m_anim.easingCurve()
        curve.setAmplitude(value)
        self.m_anim.setEasingCurve(curve)

    def overshootChanged(self, value):
        curve = self.m_anim.easingCurve()
        curve.setOvershoot(value)
        self.m_anim.setEasingCurve(curve)
示例#10
0
class PadNavigator(QGraphicsView):
    def __init__(self, size, parent=None):
        super(PadNavigator, self).__init__(parent)

        self.form = Ui_Form()

        splash = SplashItem()
        splash.setZValue(1)

        pad = FlippablePad(size)
        flipRotation = QGraphicsRotation(pad)
        xRotation = QGraphicsRotation(pad)
        yRotation = QGraphicsRotation(pad)
        flipRotation.setAxis(Qt.YAxis)
        xRotation.setAxis(Qt.YAxis)
        yRotation.setAxis(Qt.XAxis)
        pad.setTransformations([flipRotation, xRotation, yRotation])

        backItem = QGraphicsProxyWidget(pad)
        widget = QWidget()
        self.form.setupUi(widget)
        self.form.hostName.setFocus()
        backItem.setWidget(widget)
        backItem.setVisible(False)
        backItem.setFocus()
        backItem.setCacheMode(QGraphicsItem.ItemCoordinateCache)
        r = backItem.rect()
        backItem.setTransform(QTransform().rotate(180, Qt.YAxis).translate(-r.width()/2, -r.height()/2))

        selectionItem = RoundRectItem(QRectF(-60, -60, 120, 120),
                QColor(Qt.gray), pad)
        selectionItem.setZValue(0.5)

        smoothSplashMove = QPropertyAnimation(splash, b'y')
        smoothSplashOpacity = QPropertyAnimation(splash, b'opacity')
        smoothSplashMove.setEasingCurve(QEasingCurve.InQuad)
        smoothSplashMove.setDuration(250)
        smoothSplashOpacity.setDuration(250)

        smoothXSelection = QPropertyAnimation(selectionItem, b'x')
        smoothYSelection = QPropertyAnimation(selectionItem, b'y')
        smoothXRotation = QPropertyAnimation(xRotation, b'angle')
        smoothYRotation = QPropertyAnimation(yRotation, b'angle')
        smoothXSelection.setDuration(125)
        smoothYSelection.setDuration(125)
        smoothXRotation.setDuration(125)
        smoothYRotation.setDuration(125)
        smoothXSelection.setEasingCurve(QEasingCurve.InOutQuad)
        smoothYSelection.setEasingCurve(QEasingCurve.InOutQuad)
        smoothXRotation.setEasingCurve(QEasingCurve.InOutQuad)
        smoothYRotation.setEasingCurve(QEasingCurve.InOutQuad)

        smoothFlipRotation = QPropertyAnimation(flipRotation, b'angle')
        smoothFlipScale = QPropertyAnimation(pad, b'scale')
        smoothFlipXRotation = QPropertyAnimation(xRotation, b'angle')
        smoothFlipYRotation = QPropertyAnimation(yRotation, b'angle')
        flipAnimation = QParallelAnimationGroup(self)
        smoothFlipScale.setDuration(500)
        smoothFlipRotation.setDuration(500)
        smoothFlipXRotation.setDuration(500)
        smoothFlipYRotation.setDuration(500)
        smoothFlipScale.setEasingCurve(QEasingCurve.InOutQuad)
        smoothFlipRotation.setEasingCurve(QEasingCurve.InOutQuad)
        smoothFlipXRotation.setEasingCurve(QEasingCurve.InOutQuad)
        smoothFlipYRotation.setEasingCurve(QEasingCurve.InOutQuad)
        smoothFlipScale.setKeyValueAt(0, 1.0)
        smoothFlipScale.setKeyValueAt(0.5, 0.7)
        smoothFlipScale.setKeyValueAt(1, 1.0)
        flipAnimation.addAnimation(smoothFlipRotation)
        flipAnimation.addAnimation(smoothFlipScale)
        flipAnimation.addAnimation(smoothFlipXRotation)
        flipAnimation.addAnimation(smoothFlipYRotation)

        setVariablesSequence = QSequentialAnimationGroup()
        setFillAnimation = QPropertyAnimation(pad, b'fill')
        setBackItemVisibleAnimation = QPropertyAnimation(backItem, b'visible')
        setSelectionItemVisibleAnimation = QPropertyAnimation(selectionItem, b'visible')
        setFillAnimation.setDuration(0)
        setBackItemVisibleAnimation.setDuration(0)
        setSelectionItemVisibleAnimation.setDuration(0)
        setVariablesSequence.addPause(250)
        setVariablesSequence.addAnimation(setBackItemVisibleAnimation)
        setVariablesSequence.addAnimation(setSelectionItemVisibleAnimation)
        setVariablesSequence.addAnimation(setFillAnimation)
        flipAnimation.addAnimation(setVariablesSequence)

        stateMachine = QStateMachine(self)
        splashState = QState(stateMachine)
        frontState = QState(stateMachine)
        historyState = QHistoryState(frontState)
        backState = QState(stateMachine)

        frontState.assignProperty(pad, "fill", False)
        frontState.assignProperty(splash, "opacity", 0.0)
        frontState.assignProperty(backItem, "visible", False)
        frontState.assignProperty(flipRotation, "angle", 0.0)
        frontState.assignProperty(selectionItem, "visible", True)

        backState.assignProperty(pad, "fill", True)
        backState.assignProperty(backItem, "visible", True)
        backState.assignProperty(xRotation, "angle", 0.0)
        backState.assignProperty(yRotation, "angle", 0.0)
        backState.assignProperty(flipRotation, "angle", 180.0)
        backState.assignProperty(selectionItem, "visible", False)

        stateMachine.addDefaultAnimation(smoothXRotation)
        stateMachine.addDefaultAnimation(smoothYRotation)
        stateMachine.addDefaultAnimation(smoothXSelection)
        stateMachine.addDefaultAnimation(smoothYSelection)
        stateMachine.setInitialState(splashState)

        anyKeyTransition = QEventTransition(self, QEvent.KeyPress, splashState)
        anyKeyTransition.setTargetState(frontState)
        anyKeyTransition.addAnimation(smoothSplashMove)
        anyKeyTransition.addAnimation(smoothSplashOpacity)

        enterTransition = QKeyEventTransition(self, QEvent.KeyPress,
                Qt.Key_Enter, backState)
        returnTransition = QKeyEventTransition(self, QEvent.KeyPress,
                Qt.Key_Return, backState)
        backEnterTransition = QKeyEventTransition(self, QEvent.KeyPress,
                Qt.Key_Enter, frontState)
        backReturnTransition = QKeyEventTransition(self, QEvent.KeyPress,
                Qt.Key_Return, frontState)
        enterTransition.setTargetState(historyState)
        returnTransition.setTargetState(historyState)
        backEnterTransition.setTargetState(backState)
        backReturnTransition.setTargetState(backState)
        enterTransition.addAnimation(flipAnimation)
        returnTransition.addAnimation(flipAnimation)
        backEnterTransition.addAnimation(flipAnimation)
        backReturnTransition.addAnimation(flipAnimation)

        columns = size.width()
        rows = size.height()
        stateGrid = []
        for y in range(rows):
            stateGrid.append([QState(frontState) for _ in range(columns)])

        frontState.setInitialState(stateGrid[0][0])
        selectionItem.setPos(pad.iconAt(0, 0).pos())

        for y in range(rows):
            for x in range(columns):
                state = stateGrid[y][x]

                rightTransition = QKeyEventTransition(self, QEvent.KeyPress,
                        Qt.Key_Right, state)
                leftTransition = QKeyEventTransition(self, QEvent.KeyPress,
                        Qt.Key_Left, state)
                downTransition = QKeyEventTransition(self, QEvent.KeyPress,
                        Qt.Key_Down, state)
                upTransition = QKeyEventTransition(self, QEvent.KeyPress,
                        Qt.Key_Up, state)

                rightTransition.setTargetState(stateGrid[y][(x + 1) % columns])
                leftTransition.setTargetState(stateGrid[y][((x - 1) + columns) % columns])
                downTransition.setTargetState(stateGrid[(y + 1) % rows][x])
                upTransition.setTargetState(stateGrid[((y - 1) + rows) % rows][x])

                icon = pad.iconAt(x, y)
                state.assignProperty(xRotation, "angle", -icon.x() / 6.0)
                state.assignProperty(yRotation, "angle", icon.y() / 6.0)
                state.assignProperty(selectionItem, "x", icon.x())
                state.assignProperty(selectionItem, "y", icon.y())
                frontState.assignProperty(icon, "visible", True)
                backState.assignProperty(icon, "visible", False)

                setIconVisibleAnimation = QPropertyAnimation(icon, b'visible')
                setIconVisibleAnimation.setDuration(0)
                setVariablesSequence.addAnimation(setIconVisibleAnimation)

        scene = QGraphicsScene(self)
        scene.setBackgroundBrush(QBrush(QPixmap(":/images/blue_angle_swirl.jpg")))
        scene.setItemIndexMethod(QGraphicsScene.NoIndex)
        scene.addItem(pad)
        scene.setSceneRect(scene.itemsBoundingRect())
        self.setScene(scene)

        sbr = splash.boundingRect()
        splash.setPos(-sbr.width() / 2, scene.sceneRect().top() - 2)
        frontState.assignProperty(splash, "y", splash.y() - 100.0)
        scene.addItem(splash)

        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setMinimumSize(50, 50)
        self.setViewportUpdateMode(QGraphicsView.FullViewportUpdate)
        self.setCacheMode(QGraphicsView.CacheBackground)
        self.setRenderHints(QPainter.Antialiasing |
                QPainter.SmoothPixmapTransform | QPainter.TextAntialiasing)

        if QGLFormat.hasOpenGL():
            self.setViewport(QGLWidget(QGLFormat(QGL.SampleBuffers)))

        stateMachine.start()

    def resizeEvent(self, event):
        super(PadNavigator, self).resizeEvent(event)
        self.fitInView(self.scene().sceneRect(), Qt.KeepAspectRatio)
示例#11
0
class FormPaciente(QtGui.QDialog):
    def __init__(self,
                 parent=None,
                 rut=None,
                 nombres=None,
                 apellidos=None,
                 ficha=None):
        super(FormPaciente, self).__init__(parent)
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        if rut is None:  # Cuando no recibe rut crea, cuando recibe edita
            self.ui.save.clicked.connect(self.crear_paciente)
            self.ui.cancel.clicked.connect(self.exitformnuevo)
        else:
            self.colocar_datos(rut, nombres, apellidos, ficha)
            self.ui.save.clicked.connect(self.editar_pcte)
            self.ui.cancel.clicked.connect(self.exitform)

    def exitformnuevo(self):
        self.close()

    def exitform(self):
        from ctrl_grid import *
        self.close()
        self.rld = Vtn3()
        self.rld.reloadG()

    def colocar_datos(self, rut, nombres, apellidos, ficha):
        #ingresa los datos de los pacientes en las grillas

        self.ui.rut.setText(str(rut))
        self.ui.names.setText(nombres)
        self.ui.lastnames.setText(apellidos)
        self.ui.email.setText(ficha)

    def obtener_datos(self):
        #obtiene los datos del paciente del formulario
        rut = self.ui.rut.text()
        nombres = self.ui.names.text()
        apellidos = self.ui.lastnames.text()
        ficha = self.ui.email.text()
        return (rut, nombres, apellidos, ficha)

    def crear_paciente(self):
        rut, nombres, apellidos, ficha = self.obtener_datos()
        print("%s, %s, %s, %s ") % (rut, nombres, apellidos, ficha)
        try:
            model.agregar_paciente(rut, nombres, apellidos, ficha)
            self.accepted.emit()
            msgBox = QtGui.QMessageBox()
            msgBox.setText(u"El paciente ha sido creado.")
            msgBox.exec_()
            self.close()
        except (ValueError, IOError):
            errorMessageDialog = QtGui.QMessageBox(self)
            self.errorMessageDialog.setText(
                "Debe Completar los campos correctamente")
            self.errorMessageDialog.exec_()
            pass

    def editar_pcte(self):
        from ctrl_grid import *
        rut, nombres, apellidos, ficha = self.obtener_datos()
        try:
            model.editar_paciente(rut, nombres, apellidos, ficha)
            msgBox = QtGui.QMessageBox()
            msgBox.setText(u"El paciente ha sido editado.")
            msgBox.exec_()
            self.close()
            self.rld = Vtn3()
            self.rld.reloadG()
        except (ValueError, IOError):
            errorMessageDialog = QtGui.QMessageBox(self)
            self.errorMessageDialog.setText(
                "Debe Completar los campos correctamente")
            self.errorMessageDialog.exec_()
            pass
示例#12
0
class GoogleChat(QtGui.QWidget):

    URL = 'http://talkgadget.google.com/talkgadget/m'

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

        self.userName = ""
        self.password = ""

        self.form = Ui_Form()
        self.form.setupUi(self)

        self.setFixedSize(320, 480)

        self.form.userNameEdit.setFocus()
        self.form.userNameEdit.textChanged.connect(self.adjustLoginButton)
        self.form.userNameEdit.returnPressed.connect(self.inputPassword)

        self.form.passwordEdit.textChanged.connect(self.adjustLoginButton)
        self.form.passwordEdit.returnPressed.connect(self.doLogin)

        self.form.loginButton.setEnabled(False)
        self.form.loginButton.clicked.connect(self.doLogin)

        self.form.webView.loadFinished.connect(self.initialPage)
        self.form.webView.loadProgress.connect(self.form.progressBar.setValue)
        self.form.webView.setUrl(QtCore.QUrl(GoogleChat.URL))
        self.form.webView.setContextMenuPolicy(QtCore.Qt.PreventContextMenu)

        self.showStatus("Wait...")

    def showStatus(self, msg):
        self.form.statusLabel.setText(msg)
        self.form.stackedWidget.setCurrentIndex(0)

    def showError(self, msg):
        self.form.progressBar.hide()
        self.showStatus("Error: %s" % msg)

    def document(self):
        return self.form.webView.page().mainFrame().documentElement()

    def adjustLoginButton(self):
        self.userName = self.form.userNameEdit.text()
        self.password = self.form.passwordEdit.text()
        self.form.loginButton.setEnabled(bool(self.userName and self.password))
 
    def inputPassword(self):
        if self.form.userNameEdit.text():
            self.form.passwordEdit.setFocus()

    def doLogin(self):
        self.userName = self.form.userNameEdit.text()
        self.password = self.form.passwordEdit.text()
        if not (self.userName and self.password):
            return

        self.form.progressBar.setValue(0)
        self.form.progressBar.show()
        self.form.webView.loadFinished.connect(self.loginPage)
        self.form.webView.loadProgress.connect(self.form.progressBar.setValue)
        self.showStatus("Logging in...")
        userEmail = self.userName + '@gmail.com'
        self.document().findFirst('#Email').setAttribute('value', userEmail)
        self.document().findFirst('#Passwd').setAttribute('value', self.password)
        self.document().findFirst('#gaia_loginform').evaluateJavaScript('this.submit();')

    @QtCore.pyqtSlot(bool)
    def initialPage(self, ok):
        if not QtNetwork.QSslSocket.supportsSsl():
            self.showError("This example requires SSL support.")
            return

        if ok:
            email = self.document().findFirst('#Email')
            passwd = self.document().findFirst('#Passwd')
            loginForm = self.document().findFirst('#gaia_loginform')
            if not email.isNull() and not passwd.isNull() and not loginForm.isNull():
                self.form.stackedWidget.setCurrentIndex(1)
                self.form.userNameEdit.setFocus()
                self.form.webView.loadFinished.disconnect()
                self.form.webView.loadProgress.disconnect()
                return

        self.showError("Service unavailable.")

    def hideElements(self):
        self.document().findFirst('.footer-footer').removeFromDocument()
        self.document().findFirst('.title-bar-bg .title-bar').removeFromDocument()
        QtCore.QTimer.singleShot(2000, self.hideElements)

    def loginPage(self, ok):
        location = self.form.webView.url().toString()
        if not ok:
            if 'CheckCookie' in location:
                return

            self.showError("Service unavailable")
        else:
            # Check for any error message.
            e = self.document().findFirst('.errormsg')
            if e.isNull():
                self.form.stackedWidget.setCurrentIndex(2)
                QtCore.QTimer.singleShot(500, self.hideElements)
                return

            err = "Unknown login failure."
            errorMessage = e.toPlainText()

            if errorMessage:
                err = errorMessage
                err = err.simplified()

            self.showError(err)
示例#13
0
class PadNavigator(QGraphicsView):
    def __init__(self, size, parent=None):
        super(PadNavigator, self).__init__(parent)

        self.form = Ui_Form()

        splash = SplashItem()
        splash.setZValue(1)

        pad = FlippablePad(size)
        flipRotation = QGraphicsRotation(pad)
        xRotation = QGraphicsRotation(pad)
        yRotation = QGraphicsRotation(pad)
        flipRotation.setAxis(Qt.YAxis)
        xRotation.setAxis(Qt.YAxis)
        yRotation.setAxis(Qt.XAxis)
        pad.setTransformations([flipRotation, xRotation, yRotation])

        backItem = QGraphicsProxyWidget(pad)
        widget = QWidget()
        self.form.setupUi(widget)
        self.form.hostName.setFocus()
        backItem.setWidget(widget)
        backItem.setVisible(False)
        backItem.setFocus()
        backItem.setCacheMode(QGraphicsItem.ItemCoordinateCache)
        r = backItem.rect()
        backItem.setTransform(QTransform().rotate(180, Qt.YAxis).translate(
            -r.width() / 2, -r.height() / 2))

        selectionItem = RoundRectItem(QRectF(-60, -60, 120, 120),
                                      QColor(Qt.gray), pad)
        selectionItem.setZValue(0.5)

        smoothSplashMove = QPropertyAnimation(splash, "y")
        smoothSplashOpacity = QPropertyAnimation(splash, "opacity")
        smoothSplashMove.setEasingCurve(QEasingCurve.InQuad)
        smoothSplashMove.setDuration(250)
        smoothSplashOpacity.setDuration(250)

        smoothXSelection = QPropertyAnimation(selectionItem, "x")
        smoothYSelection = QPropertyAnimation(selectionItem, "y")
        smoothXRotation = QPropertyAnimation(xRotation, "angle")
        smoothYRotation = QPropertyAnimation(yRotation, "angle")
        smoothXSelection.setDuration(125)
        smoothYSelection.setDuration(125)
        smoothXRotation.setDuration(125)
        smoothYRotation.setDuration(125)
        smoothXSelection.setEasingCurve(QEasingCurve.InOutQuad)
        smoothYSelection.setEasingCurve(QEasingCurve.InOutQuad)
        smoothXRotation.setEasingCurve(QEasingCurve.InOutQuad)
        smoothYRotation.setEasingCurve(QEasingCurve.InOutQuad)

        smoothFlipRotation = QPropertyAnimation(flipRotation, "angle")
        smoothFlipScale = QPropertyAnimation(pad, "scale")
        smoothFlipXRotation = QPropertyAnimation(xRotation, "angle")
        smoothFlipYRotation = QPropertyAnimation(yRotation, "angle")
        flipAnimation = QParallelAnimationGroup(self)
        smoothFlipScale.setDuration(500)
        smoothFlipRotation.setDuration(500)
        smoothFlipXRotation.setDuration(500)
        smoothFlipYRotation.setDuration(500)
        smoothFlipScale.setEasingCurve(QEasingCurve.InOutQuad)
        smoothFlipRotation.setEasingCurve(QEasingCurve.InOutQuad)
        smoothFlipXRotation.setEasingCurve(QEasingCurve.InOutQuad)
        smoothFlipYRotation.setEasingCurve(QEasingCurve.InOutQuad)
        smoothFlipScale.setKeyValueAt(0, 1.0)
        smoothFlipScale.setKeyValueAt(0.5, 0.7)
        smoothFlipScale.setKeyValueAt(1, 1.0)
        flipAnimation.addAnimation(smoothFlipRotation)
        flipAnimation.addAnimation(smoothFlipScale)
        flipAnimation.addAnimation(smoothFlipXRotation)
        flipAnimation.addAnimation(smoothFlipYRotation)

        setVariablesSequence = QSequentialAnimationGroup()
        setFillAnimation = QPropertyAnimation(pad, "fill")
        setBackItemVisibleAnimation = QPropertyAnimation(backItem, "visible")
        setSelectionItemVisibleAnimation = QPropertyAnimation(
            selectionItem, "visible")
        setFillAnimation.setDuration(0)
        setBackItemVisibleAnimation.setDuration(0)
        setSelectionItemVisibleAnimation.setDuration(0)
        setVariablesSequence.addPause(250)
        setVariablesSequence.addAnimation(setBackItemVisibleAnimation)
        setVariablesSequence.addAnimation(setSelectionItemVisibleAnimation)
        setVariablesSequence.addAnimation(setFillAnimation)
        flipAnimation.addAnimation(setVariablesSequence)

        stateMachine = QStateMachine(self)
        splashState = QState(stateMachine)
        frontState = QState(stateMachine)
        historyState = QHistoryState(frontState)
        backState = QState(stateMachine)

        frontState.assignProperty(pad, "fill", False)
        frontState.assignProperty(splash, "opacity", 0.0)
        frontState.assignProperty(backItem, "visible", False)
        frontState.assignProperty(flipRotation, "angle", 0.0)
        frontState.assignProperty(selectionItem, "visible", True)

        backState.assignProperty(pad, "fill", True)
        backState.assignProperty(backItem, "visible", True)
        backState.assignProperty(xRotation, "angle", 0.0)
        backState.assignProperty(yRotation, "angle", 0.0)
        backState.assignProperty(flipRotation, "angle", 180.0)
        backState.assignProperty(selectionItem, "visible", False)

        stateMachine.addDefaultAnimation(smoothXRotation)
        stateMachine.addDefaultAnimation(smoothYRotation)
        stateMachine.addDefaultAnimation(smoothXSelection)
        stateMachine.addDefaultAnimation(smoothYSelection)
        stateMachine.setInitialState(splashState)

        anyKeyTransition = QEventTransition(self, QEvent.KeyPress, splashState)
        anyKeyTransition.setTargetState(frontState)
        anyKeyTransition.addAnimation(smoothSplashMove)
        anyKeyTransition.addAnimation(smoothSplashOpacity)

        enterTransition = QKeyEventTransition(self, QEvent.KeyPress,
                                              Qt.Key_Enter, backState)
        returnTransition = QKeyEventTransition(self, QEvent.KeyPress,
                                               Qt.Key_Return, backState)
        backEnterTransition = QKeyEventTransition(self, QEvent.KeyPress,
                                                  Qt.Key_Enter, frontState)
        backReturnTransition = QKeyEventTransition(self, QEvent.KeyPress,
                                                   Qt.Key_Return, frontState)
        enterTransition.setTargetState(historyState)
        returnTransition.setTargetState(historyState)
        backEnterTransition.setTargetState(backState)
        backReturnTransition.setTargetState(backState)
        enterTransition.addAnimation(flipAnimation)
        returnTransition.addAnimation(flipAnimation)
        backEnterTransition.addAnimation(flipAnimation)
        backReturnTransition.addAnimation(flipAnimation)

        columns = size.width()
        rows = size.height()
        stateGrid = []
        for y in range(rows):
            stateGrid.append([QState(frontState) for _ in range(columns)])

        frontState.setInitialState(stateGrid[0][0])
        selectionItem.setPos(pad.iconAt(0, 0).pos())

        for y in range(rows):
            for x in range(columns):
                state = stateGrid[y][x]

                rightTransition = QKeyEventTransition(self, QEvent.KeyPress,
                                                      Qt.Key_Right, state)
                leftTransition = QKeyEventTransition(self, QEvent.KeyPress,
                                                     Qt.Key_Left, state)
                downTransition = QKeyEventTransition(self, QEvent.KeyPress,
                                                     Qt.Key_Down, state)
                upTransition = QKeyEventTransition(self, QEvent.KeyPress,
                                                   Qt.Key_Up, state)

                rightTransition.setTargetState(stateGrid[y][(x + 1) % columns])
                leftTransition.setTargetState(
                    stateGrid[y][((x - 1) + columns) % columns])
                downTransition.setTargetState(stateGrid[(y + 1) % rows][x])
                upTransition.setTargetState(stateGrid[((y - 1) + rows) %
                                                      rows][x])

                icon = pad.iconAt(x, y)
                state.assignProperty(xRotation, "angle", -icon.x() / 6.0)
                state.assignProperty(yRotation, "angle", icon.y() / 6.0)
                state.assignProperty(selectionItem, "x", icon.x())
                state.assignProperty(selectionItem, "y", icon.y())
                frontState.assignProperty(icon, "visible", True)
                backState.assignProperty(icon, "visible", False)

                setIconVisibleAnimation = QPropertyAnimation(icon, "visible")
                setIconVisibleAnimation.setDuration(0)
                setVariablesSequence.addAnimation(setIconVisibleAnimation)

        scene = QGraphicsScene(self)
        scene.setBackgroundBrush(
            QBrush(QPixmap(":/images/blue_angle_swirl.jpg")))
        scene.setItemIndexMethod(QGraphicsScene.NoIndex)
        scene.addItem(pad)
        scene.setSceneRect(scene.itemsBoundingRect())
        self.setScene(scene)

        sbr = splash.boundingRect()
        splash.setPos(-sbr.width() / 2, scene.sceneRect().top() - 2)
        frontState.assignProperty(splash, "y", splash.y() - 100.0)
        scene.addItem(splash)

        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setMinimumSize(50, 50)
        self.setViewportUpdateMode(QGraphicsView.FullViewportUpdate)
        self.setCacheMode(QGraphicsView.CacheBackground)
        self.setRenderHints(QPainter.Antialiasing
                            | QPainter.SmoothPixmapTransform
                            | QPainter.TextAntialiasing)

        if QGLFormat.hasOpenGL():
            self.setViewport(QGLWidget(QGLFormat(QGL.SampleBuffers)))

        stateMachine.start()

    def resizeEvent(self, event):
        super(PadNavigator, self).resizeEvent(event)
        self.fitInView(self.scene().sceneRect(), Qt.KeepAspectRatio)
示例#14
0
class FormMedico(QtGui.QDialog):

    def __init__(self,parent = None, rut=None, nombres = None, apellidos = None, ficha = None):
        super(FormMedico, self).__init__(parent)
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        if rut is None:# Cuando no recibe rut crea, cuando recibe edita
            self.ui.save.clicked.connect(self.crear_medico)
        else:
            self.colocar_datos(rut, nombres, apellidos, ficha)
            self.ui.save.clicked.connect(self.editar_mdco)
            self.ui.cancel.clicked.connect(self.exitform)

    def exitform(self):
        from ctrl_grid2 import *
        self.close()
        self.rld = Vtn4()
        self.rld.reloadG()

    def colocar_datos(self, rut, nombres, apellidos, ficha):
        #ingresa los datos de los medicos en las grillas

        self.ui.rut.setText(str(rut))
        self.ui.names.setText(nombres)
        self.ui.lastnames.setText(apellidos)
        self.ui.email.setText(ficha)

    def obtener_datos(self):
        #obtiene los datos del medico del formulario
        rut = self.ui.rut.text()
        nombres = self.ui.names.text()
        apellidos = self.ui.lastnames.text()
        ficha = self.ui.email.text()
        return (rut, nombres, apellidos, ficha)

    def crear_medico(self):
        rut, nombres, apellidos, ficha = self.obtener_datos()
        print ("%s, %s, %s, %s ")%(rut, nombres, apellidos, ficha)
        try:
            model.agregar_paciente(rut, nombres, apellidos, ficha)
            self.accepted.emit()
            msgBox = QtGui.QMessageBox()
            msgBox.setText(u"El paciente ha sido creado.")
            msgBox.exec_()
            self.close()
        except(ValueError, IOError):
            errorMessageDialog = QtGui.QMessageBox(self)
            self.errorMessageDialog.setText("Debe Completar los campos correctamente")
            self.errorMessageDialog.exec_()
            pass

    def editar_mdco(self):
        from ctrl_grid2 import *
        rut, Especialidad, nombres, apellidos = self.obtener_datos()
        try:
            model.editar_medico(rut, Especialidad,nombres, apellidos)
            msgBox = QtGui.QMessageBox()
            msgBox.setText(u"El medico ha sido editado.")
            msgBox.exec_()
            self.close()
            self.rld = Vtn4()
            self.rld.reloadG()
        except (ValueError, IOError):
            errorMessageDialog = QtGui.QMessageBox(self)
            self.errorMessageDialog.setText("Debe Completar los campos correctamente")
            self.errorMessageDialog.exec_()
            pass
示例#15
0
class GoogleChat(QtGui.QWidget):
    URL = 'http://talkgadget.google.com/talkgadget/m'

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

        self.userName = ""
        self.password = ""

        self.form = Ui_Form()
        self.form.setupUi(self)

        self.setFixedSize(320, 480)

        self.form.userNameEdit.setFocus()
        self.form.userNameEdit.textChanged.connect(self.adjustLoginButton)
        self.form.userNameEdit.returnPressed.connect(self.inputPassword)

        self.form.passwordEdit.textChanged.connect(self.adjustLoginButton)
        self.form.passwordEdit.returnPressed.connect(self.doLogin)

        self.form.loginButton.setEnabled(False)
        self.form.loginButton.clicked.connect(self.doLogin)

        self.form.webView.loadFinished.connect(self.initialPage)
        self.form.webView.loadProgress.connect(self.form.progressBar.setValue)
        self.form.webView.setUrl(QtCore.QUrl(GoogleChat.URL))
        self.form.webView.setContextMenuPolicy(QtCore.Qt.PreventContextMenu)

        self.showStatus("Wait...")

    def showStatus(self, msg):
        self.form.statusLabel.setText(msg)
        self.form.stackedWidget.setCurrentIndex(0)

    def showError(self, msg):
        self.form.progressBar.hide()
        self.showStatus("Error: %s" % msg)

    def document(self):
        return self.form.webView.page().mainFrame().documentElement()

    def adjustLoginButton(self):
        self.userName = self.form.userNameEdit.text()
        self.password = self.form.passwordEdit.text()
        self.form.loginButton.setEnabled(bool(self.userName and self.password))

    def inputPassword(self):
        if self.form.userNameEdit.text():
            self.form.passwordEdit.setFocus()

    def doLogin(self):
        self.userName = self.form.userNameEdit.text()
        self.password = self.form.passwordEdit.text()
        if not (self.userName and self.password):
            return

        self.form.progressBar.setValue(0)
        self.form.progressBar.show()
        self.form.webView.loadFinished.connect(self.loginPage)
        self.form.webView.loadProgress.connect(self.form.progressBar.setValue)
        self.showStatus("Logging in...")
        userEmail = self.userName + '@gmail.com'
        self.document().findFirst('#Email').setAttribute('value', userEmail)
        self.document().findFirst('#Passwd').setAttribute(
            'value', self.password)
        self.document().findFirst('#gaia_loginform').evaluateJavaScript(
            'this.submit();')

    @QtCore.pyqtSlot(bool)
    def initialPage(self, ok):
        if not QtNetwork.QSslSocket.supportsSsl():
            self.showError("This example requires SSL support.")
            return

        if ok:
            email = self.document().findFirst('#Email')
            passwd = self.document().findFirst('#Passwd')
            loginForm = self.document().findFirst('#gaia_loginform')
            if not email.isNull() and not passwd.isNull(
            ) and not loginForm.isNull():
                self.form.stackedWidget.setCurrentIndex(1)
                self.form.userNameEdit.setFocus()
                self.form.webView.loadFinished.disconnect()
                self.form.webView.loadProgress.disconnect()
                return

        self.showError("Service unavailable.")

    def hideElements(self):
        self.document().findFirst('.footer-footer').removeFromDocument()
        self.document().findFirst(
            '.title-bar-bg .title-bar').removeFromDocument()
        QtCore.QTimer.singleShot(2000, self.hideElements)

    def loginPage(self, ok):
        location = self.form.webView.url().toString()
        if not ok:
            if 'CheckCookie' in location:
                return

            self.showError("Service unavailable")
        else:
            # Check for any error message.
            e = self.document().findFirst('.errormsg')
            if e.isNull():
                self.form.stackedWidget.setCurrentIndex(2)
                QtCore.QTimer.singleShot(500, self.hideElements)
                return

            err = "Unknown login failure."
            errorMessage = e.toPlainText()

            if errorMessage:
                err = errorMessage
                err = err.simplified()

            self.showError(err)