Example #1
0
class ImageMediaView(MediaView):
    def __init__(self, media, parent):
        super(ImageMediaView, self).__init__(media, parent)
        self.widget = QLabel(parent)
        self.widget.setGeometry(media['geometry'])
        self.img = QImage()
        self.set_default_widget_prop()

    @Slot()
    def play(self):
        self.finished = 0
        path = '%s/%s' % (self.save_dir, self.options['uri'])
        rect = self.widget.geometry()
        self.img.load(path)
        self.img = self.img.scaled(rect.width(), rect.height(),
                                   Qt.IgnoreAspectRatio,
                                   Qt.SmoothTransformation)
        self.widget.setPixmap(QPixmap.fromImage(self.img))
        self.widget.show()
        self.widget.raise_()
        if float(self.duration) > 0:
            self.play_timer.setInterval(int(float(self.duration) * 1000))
            self.play_timer.start()
        self.started_signal.emit()

    @Slot()
    def stop(self, delete_widget=False):
        #---- kong ----
        if not self.widget:
            return False
        del self.img
        self.img = QImage()
        #----
        super(ImageMediaView, self).stop(delete_widget)
        return True
Example #2
0
class ImageMediaView(MediaView):
    def __init__(self, media, parent):
        super(ImageMediaView, self).__init__(media, parent)
        self._widget = QLabel(parent)
        self._widget.setGeometry(media['_geometry'])
        self._img = QImage()
        self.set_default_widget_prop()

    @Slot()
    def play(self):
        self._finished = 0
        path = "%s/%s" % (self._save_dir, self._options['uri'])
        rect = self._widget.geometry()
        self._img.load(path)
        self._img = self._img.scaled(rect.width(), rect.height(),
                                     Qt.IgnoreAspectRatio,
                                     Qt.SmoothTransformation)

        self._widget.setPixmap(QPixmap.fromImage(self._img))
        self._widget.show()
        self._widget.raise_()

        self._play_timer.setInterval(int(float(self._duration) * 1000))
        self._play_timer.start()
        self.started_signal.emit()
    def DisplayWelcome(self):
        WelcomeScreen = QApplication(sys.argv)

        appLabel = QLabel()
        appLabel.setText("Welcome To SparkControl: Python")

        appLabel.setAlignment(Qt.AlignCenter)
        appLabel.setWindowTitle("Spark Control Python")
        appLabel.setGeometry(300, 300, 250, 175)

        #Draw the label
        appLabel.show()
 def DisplayWelcome(self):
     WelcomeScreen = QApplication(sys.argv)
 
     appLabel=QLabel()
     appLabel.setText("Welcome To SparkControl: Python")
 
     appLabel.setAlignment(Qt.AlignCenter)
     appLabel.setWindowTitle("Spark Control Python")
     appLabel.setGeometry(300,300,250,175)
 
 #Draw the label
     appLabel.show()
Example #5
0
    def firstPage(self):
        
        for i in range( self.mainLayout.count() ):
            item = self.mainLayout.itemAt(0)
            item.widget().setParent( None )
        
        title = QLabel( "<p style='color:rgb( 137,129,120 )'>Welcome to the PingoTools Installer</p>" )
        title.setFixedHeight( 50 )
        titleFont  = QFont()
        titleFont.setPixelSize( 18 )
        titleFont.setBold( True )
        titleFont.setFamily( "Helvetica [Cronyx]" )
        title.setAlignment( QtCore.Qt.AlignCenter )
        title.setFont( titleFont )
        
        description = QLabel()
        description.setAlignment( QtCore.Qt.AlignCenter )
        
        buttonsWidget = QWidget(); buttonsWidget.setMaximumHeight( 50 )
        buttonsLayout = QHBoxLayout( buttonsWidget )
        emptyArea = QLabel()
        buttonNext = QPushButton( 'Next > ' )
        buttonCancel = QPushButton( 'Cancel' )
        buttonsLayout.addWidget( emptyArea )
        buttonsLayout.addWidget( buttonNext ); buttonNext.setFixedWidth( 100 )
        buttonsLayout.addWidget( buttonCancel ); buttonCancel.setFixedWidth( 100 )
        
        self.mainLayout.addWidget( title )
        self.mainLayout.addWidget( description )
        self.mainLayout.addWidget( buttonsWidget )
        
        origWidth = 500

        frontImage = QImage()
        frontImage.load( os.path.dirname( __file__ ) + '/images/pingoTools_main.jpg' )
        trValue = QTransform().scale( float(origWidth)/frontImage.width(), float(origWidth)/frontImage.width() )
        transformedImage = frontImage.transformed( trValue )
        pixmap     = QPixmap.fromImage( transformedImage )
        description.setPixmap( pixmap )
        description.setGeometry( 0,0, transformedImage.width() , transformedImage.height() )
        description.paintEvent(QPaintEvent(QtCore.QRect( 0,0,self.width(), self.height() )))
        
        QtCore.QObject.connect( buttonNext, QtCore.SIGNAL( 'clicked()' ), self.secondPage )
        QtCore.QObject.connect( buttonCancel, QtCore.SIGNAL( 'clicked()' ), self.cmd_cancel )
Example #6
0
class managebkm(QDialog):
	def __init__(self, parent=None):
		super(managebkm, self).__init__(parent)
		appicom = QIcon(":/icons/njnlogo.png")
		self.setWindowIcon(appicom)
		self.setWindowTitle("Nigandu | Manage Book Marks")
		self.setFixedSize(463, 242)

		self.verticalLayoutWidget = QWidget(self)
		self.verticalLayoutWidget.setGeometry(QRect(350, 30, 101, 201))
		self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
		self.verticalLayout = QVBoxLayout(self.verticalLayoutWidget)
		self.verticalLayout.setContentsMargins(0, 0, 0, 0)
		self.verticalLayout.setObjectName("verticalLayout")

		self.sortbtn = QPushButton(self.verticalLayoutWidget)
		self.sortbtn.setText("&Sort")
		self.verticalLayout.addWidget(self.sortbtn)

		self.deletebtn = QPushButton(self.verticalLayoutWidget)
		self.deletebtn.setText("&Delete")
		self.verticalLayout.addWidget(self.deletebtn)

		self.deleteallbtn = QPushButton(self.verticalLayoutWidget)
		self.deleteallbtn.setText("Delete &All")
		self.verticalLayout.addWidget(self.deleteallbtn)

		self.closebtn = QPushButton(self.verticalLayoutWidget)
		self.closebtn.setText("&Close")
		self.verticalLayout.addWidget(self.closebtn)

		self.listWidget = QListWidget(self)
		self.listWidget.setGeometry(QRect(10, 30, 331, 201))

		self.label = QLabel(self)
		self.label.setGeometry(QRect(20, 10, 91, 25))
		font = QFont()
		font.setPointSize(10)
		self.label.setFont(font)
		self.label.setBuddy(self.listWidget)
		self.label.setText("Book Mark List:")
    def organizeContent(self, widget):
        # get style metrics
        leftMargin = self.app.style().pixelMetric(QStyle.PM_LayoutLeftMargin)
        topMargin = self.app.style().pixelMetric(QStyle.PM_LayoutTopMargin)
        standHeight = self.app.style().pixelMetric(QStyle.PM_ButtonMargin) +\
                      self.app.fontMetrics().height()
        doubleStandHeight = standHeight * 2
        hsepara = self.app.style().pixelMetric(QStyle.PM_LayoutHorizontalSpacing)
        vsepara = self.app.style().pixelMetric(QStyle.PM_LayoutVerticalSpacing)
        # calculate grids
        col0Left = leftMargin
        col1Left = leftMargin + doubleStandHeight + vsepara
        col2Left = leftMargin + doubleStandHeight + standHeight + 2*vsepara
        col3Left = leftMargin + 2*doubleStandHeight + standHeight + 4*vsepara
        row0Top = topMargin
        row1Top = topMargin + standHeight + hsepara
        row2Top = topMargin + 3*standHeight + 2*hsepara
        row3Top = topMargin + 4*standHeight + 3*hsepara

        btnUp = QPushButton('Up', widget)
        btnUp.setGeometry(col1Left, row1Top, standHeight, doubleStandHeight)
        btnLeft = QPushButton('Left', widget)
        btnLeft.setGeometry(col0Left, row2Top, doubleStandHeight, standHeight)
        txtQuant = QLineEdit(widget)
        txtQuant.setGeometry(col1Left, row2Top, standHeight, standHeight)
        txtQuant.setAlignment(Qt.AlignVCenter | Qt.AlignCenter)
        btnRight = QPushButton('Right', widget)
        btnRight.setGeometry(col2Left, row2Top, doubleStandHeight, standHeight)
        btnDown = QPushButton('Dn', widget)
        btnDown.setGeometry(col1Left, row3Top, standHeight, doubleStandHeight)
        lb3 = QLabel('Elevation:', widget)
        lb3.setGeometry(col3Left, row2Top, lb3.sizeHint().width(), standHeight)
        wi = self.app.fontMetrics().width('Horizontal:') + 2
        lb4 = QLabel('Horizontal:', widget)
        lb4.setGeometry(col3Left, row3Top, wi, standHeight)
        col4Left = leftMargin + 2*doubleStandHeight + standHeight + 5*vsepara + wi
        txtElev = QLineEdit(widget)
        txtElev.setGeometry(col4Left, row2Top, doubleStandHeight, standHeight)
        txtElev.setAlignment(Qt.AlignVCenter | Qt.AlignCenter)
        txtHoriz = QLineEdit(widget)
        txtHoriz.setGeometry(col4Left, row3Top, doubleStandHeight, standHeight)
        txtHoriz.setAlignment(Qt.AlignVCenter | Qt.AlignCenter)
        lb2 = QLabel('Angles in degrees', widget)
        lb2.setGeometry(col3Left, row2Top - standHeight - hsepara, wi + hsepara + doubleStandHeight, standHeight)
        lb2.setAlignment(Qt.AlignVCenter | Qt.AlignCenter) #Qt.AlignVCenter
        totalWi = col4Left + doubleStandHeight - col0Left
        totalHi = row3Top + doubleStandHeight - row0Top
        lb1 = QLabel('Camera position control panel', widget)
        lb1.setGeometry(col0Left, row0Top, totalWi, standHeight)
        lb1.setAlignment(Qt.AlignVCenter | Qt.AlignCenter)
        lb1.setFrameStyle(QFrame.Box)
Example #8
0
class ImageMediaView(MediaView):
    def __init__(self, media, parent):
        super(ImageMediaView, self).__init__(media, parent)
        self._widget = QLabel(parent)
        self._widget.setGeometry(media['_geometry'])
        self._img = QImage()
        self.set_default_widget_prop()

    @Slot()
    def play(self):
        self._finished = 0
        path = "%s/%s" % (self._save_dir, self._options['uri'])
        rect = self._widget.geometry()
        self._img.load(path)
        self._img = self._img.scaled(rect.width(), rect.height(),
                                     Qt.IgnoreAspectRatio, Qt.SmoothTransformation)

        self._widget.setPixmap(QPixmap.fromImage(self._img))
        self._widget.show()
        self._widget.raise_()

        self._play_timer.setInterval(int(float(self._duration) * 1000))
        self._play_timer.start()
        self.started_signal.emit()
Example #9
0
#! /usr/bin/env/python
# -*- coding:utf-8 -*-
__author__ = 'tim'

import sys
from PySide.QtCore import Qt
from PySide.QtGui import QApplication, QLabel

if __name__ == '__main__':
    app = QApplication(sys.argv)

    label = QLabel()
    label.setText("hello world")
    label.setAlignment(Qt.AlignCenter)
    label.setWindowTitle('My First Application')
    label.setGeometry(300, 300, 350, 100)

    label.show()

    sys.exit(app.exec_())
class Deformation_GUI(QWidget):
    #Initialize the variable
    def __init__(self, oriPath, protoPath, oriPointsPath, protoPointsPath,
                 regionsPath):
        super(Deformation_GUI, self).__init__()
        localParas, points = preprocess(oriPath, protoPath, oriPointsPath,
                                        protoPointsPath, regionsPath, 'L2')
        self.oriImg, self.protoImg, self.regionsPoints, self.is_in_regions_fun, self.distance_funs, self.affine_funs = localParas
        self.oriPlotDict, self.protoPlotDict, self.oriPoints, self.protoPoints = points
        self.oriPoints = np.array(self.oriPoints)
        self.protoPoints = np.array(self.protoPoints)
        self.e = 2
        self.alpha = 1
        self.oriPath = oriPath
        self.protoPath = protoPath
        self.oriPointsPath = ''
        self.protoPointsPath = ''
        self.regionsPath = regionsPath
        self.transform = 'Morphing'
        self.newImg = None
        self.initUI()

    #Initialize the GUI
    def initUI(self):
        #Set Window
        QToolTip.setFont(QFont('Serif', 10))
        self.setGeometry(280, 210, 800, 450)
        self.setWindowTitle('Image Registration Based on Control Points')
        #Set Algorithm
        self.comboAffineLabel = QLabel(self)
        self.comboAffineLabel.setText('Algorithm:')
        self.comboAffineLabel.setGeometry(60, 270, 230, 30)
        self.comboAffine = QComboBox(self)
        self.comboAffine.addItem("Morphing")
        self.comboAffine.addItem("Local Affine Transformation")
        self.comboAffine.addItem("Moving Least Squares")
        self.comboAffine.setGeometry(22, 290, 225, 30)
        self.comboAffine.activated[str].connect(self.affineChoiceChange)
        #Choose Human Face Image
        self.oriBtn = QPushButton('Human Face Image', self)
        self.oriBtn.setToolTip('Human Face Image')
        self.oriBtn.setGeometry(20, 330, 230, 30)
        self.oriBtn.clicked.connect(self.showOriDialog)
        #Choose Ape or another Human image
        self.protoBtn = QPushButton('Ape or Human image', self)
        self.protoBtn.setToolTip('Ape or Human image')
        self.protoBtn.setGeometry(310, 330, 230, 30)
        self.protoBtn.clicked.connect(self.showProtoDialog)
        #parameter e
        self.eLabel = QLabel(self)
        self.eLabel.setText('E Value:0.00')
        self.eLabel.setGeometry(550, 300, 200, 30)
        self.eSld = QSlider(Qt.Horizontal, self)
        self.eSld.setRange(0, 10**5)
        self.eSld.setFocusPolicy(Qt.NoFocus)
        self.eSld.setGeometry(550, 330, 120, 30)
        self.eSld.valueChanged[int].connect(self.changeEValue)
        #parameter alpha
        self.aLabel = QLabel(self)
        self.aLabel.setText('Alpha Value:0.00')
        self.aLabel.setGeometry(680, 300, 200, 30)
        self.aSld = QSlider(Qt.Horizontal, self)
        self.aSld.setRange(0, 10**5)
        self.aSld.setFocusPolicy(Qt.NoFocus)
        self.aSld.setGeometry(680, 330, 100, 30)
        self.aSld.valueChanged[int].connect(self.changeAlphaValue)
        # The Image
        self.oriTextLabel = QLabel(self)
        self.protoTextLabel = QLabel(self)
        self.transTextLabel = QLabel(self)
        self.oriTextLabel.setText('The Human Image')
        self.protoTextLabel.setText('The Ape or another Human Image')
        self.transTextLabel.setText('Deformation Image')
        self.oriTextLabel.move(70, 5)
        self.protoTextLabel.move(350, 5)
        self.transTextLabel.move(580, 5)
        self.oriLabel = QLabel(self)
        self.protoLabel = QLabel(self)
        self.transLabel = QLabel(self)
        pixmap = QPixmap(self.oriPath)
        pixmap2 = QPixmap(self.protoPath)
        self.oriLabel.setPixmap(pixmap)
        self.protoLabel.setPixmap(pixmap2)
        self.transLabel.setPixmap(pixmap)
        #Set Position
        self.oriLabel.setGeometry(20, 20, 230, 230)
        self.protoLabel.setGeometry(290, 20, 230, 230)
        self.transLabel.setGeometry(560, 20, 230, 230)
        self.oriLabel.setScaledContents(True)
        self.protoLabel.setScaledContents(True)
        self.transLabel.setScaledContents(True)
        #import points
        self.loadOriBtn = QPushButton('Deformed Points', self)
        self.loadOriBtn.setToolTip('Load Control Points From Txt File')
        self.loadOriBtn.setGeometry(20, 365, 230, 30)
        self.loadOriBtn.clicked.connect(self.showLoadOriDialog)
        self.loadProtoBtn = QPushButton('Control Points', self)
        self.loadProtoBtn.setToolTip('Load Control Points From Txt File')
        self.loadProtoBtn.setGeometry(310, 365, 230, 30)
        self.loadProtoBtn.clicked.connect(self.showLoadProtoDialog)
        #Deformed
        self.confirmBtn = QPushButton('Deformed', self)
        self.confirmBtn.setToolTip('Deformed')
        self.confirmBtn.setGeometry(580, 365, 150, 30)
        self.confirmBtn.clicked.connect(self.transformAction)
        self.show()

    #Deformed Generate
    def transformAction(self):

        try:
            #three algorithm
            if self.transform == 'Morphing':
                self.oriImg = np.array(Image.open(self.oriPath))
                self.protoImg = np.array(Image.open(self.protoPath))
                newImg = morphingAction((self.oriPath).encode('utf-8'),
                                        self.protoPath.encode('utf-8'),
                                        self.oriPointsPath.encode('utf-8'),
                                        self.protoPointsPath.encode('utf-8'),
                                        self.alpha)
            else:
                localParas, points = preprocess(self.oriPath, self.protoPath,
                                                self.oriPointsPath,
                                                self.protoPointsPath,
                                                self.regionsPath, 'L2')
                if points == None:
                    QtGui.QMessageBox.information(self, "Error", localParas)
                    return
                self.oriImg, self.protoImg, self.regionsPoints, self.is_in_regions_fun, self.distance_funs, self.affine_funs = localParas
                self.oriPlotDict, self.protoPlotDict, self.oriPoints, self.protoPoints = points
                if self.oriImg.shape[len(self.oriImg.shape) -
                                     1] != self.protoImg.shape[
                                         len(self.protoImg.shape) - 1]:
                    QtGui.QMessageBox.information(
                        self, "Error",
                        "The type of the figures is not the same, please choose another figure"
                    )
                    return
                if self.transform == 'Local Affine Transformation':
                    newImg = local_affine(self.oriImg, self.protoImg, self.e,
                                          self.regionsPoints,
                                          self.is_in_regions_fun,
                                          self.distance_funs, self.affine_funs)
                elif self.transform == "Moving Least Squares":
                    newImg = MLS(self.oriImg, self.protoImg, self.oriPoints,
                                 self.protoPoints, self.alpha)
        except BaseException:
            QtGui.QMessageBox.information(
                self, "Error",
                "There are error in the point choice or other things.")
            newImg = morphingAction((self.oriPath).encode('utf-8'),
                                    self.protoPath.encode('utf-8'),
                                    self.oriPointsPath.encode('utf-8'),
                                    self.protoPointsPath.encode('utf-8'),
                                    self.alpha)

        self.newImg = np.uint8(newImg)
        newImg = rgb2bgr(np.uint8(newImg))
        qimage = QImage(newImg, newImg.shape[1], newImg.shape[0],
                        QImage.Format_ARGB32)
        pixmap_array = QPixmap.fromImage(qimage)
        self.transLabel.setPixmap(pixmap_array)

    def showProtoDialog(self):
        fname, _ = QtGui.QFileDialog.getOpenFileName(
            self, 'Open file', '/home', "Image Files (*.png *.jpg *.bmp)")
        if fname != None and fname != '':
            self.protoPath = fname
            self.protoLabel.setPixmap(QPixmap(self.protoPath))

    def showLoadOriDialog(self):
        fname, _ = QtGui.QFileDialog.getOpenFileName(self, 'Open file',
                                                     '/home',
                                                     "Text files (*.txt)")
        if fname != None and fname != '':
            self.oriPointsPath = fname

    def showLoadProtoDialog(self):
        fname, _ = QtGui.QFileDialog.getOpenFileName(self, 'Open file',
                                                     '/home',
                                                     "Text files (*.txt)")
        if fname != None and fname != '':
            self.protoPointsPath = fname
        else:
            self.protoPointsPath = ''

    def showOriDialog(self):
        fname, _ = QtGui.QFileDialog.getOpenFileName(
            self, 'Open file', '/home', "Image Files (*.png *.jpg *.bmp)")
        if fname != None and fname != '':
            self.oriPath = fname
            print(self.oriPath)
            self.oriLabel.setPixmap(QPixmap(self.oriPath))

    #e value in Local Affine Algorithm
    def changeEValue(self, x):
        self.e = 4.0 * x / 10**5
        self.eLabel.setText('E Value:' + str('%.2f' % self.e))

    #alpha value in MLS and Morphing Algorithm
    #the alpha range is  different
    def changeAlphaValue(self, x):
        if self.transform == 'Moving Least Squares':
            self.alpha = 2.0 * x / 10**5
        elif self.transform == 'Morphing':
            self.alpha = 1.0 * x / 10**5
        self.aLabel.setText('Alpha Value:' + str('%.2f' % self.alpha))

    # 3 Algorithm
    def affineChoiceChange(self, item):
        if self.transform in ['Moving Least Squares', 'Morphing'] and item in [
                'Moving Least Squares', 'Morphing'
        ] and item != self.transform:
            self.alpha = 0.0
            self.aSld.setValue(self.alpha)
        self.transform = item
Example #11
0
class UiMain(QMainWindow):
    """ The main gui interface, invokes all windows and ties everything
     together
    """
    def __init__(self):
        """ automatically called __init__ function """

        super(UiMain, self).__init__()

        # initialize all the variables that are going to be defined in the
        # future
        self.update_dialog = None
        self.update_dialog_lbl = None
        self.app_select_box = None
        self.selector_lbl = None
        self.current_playing_lbl = None
        self.current_playing = None
        self.misc_messages = None
        self.start_btn = None
        self.output_dir_lbl = None
        self.select_output_dir_btn = None
        self.output_cur_dir_lbl = None
        self.active_items_list = None
        self.inactive_items_list = None
        self.switch_active_item_button_off = None
        self.switch_active_item_button_on = None
        self.switch_output_split_btn = None
        self.switch_output_split_lbl = None

        # initialize the system tray
        # self.system_tray = QSystemTrayIcon(self)
        # self.system_tray.setIcon(QIcon(resource_path('icon.png')))
        # self.system_tray.show()
        # self.system_tray.setToolTip('SMG')
        # self.system_tray.activated.connect(self.on_systray_activated)

        # initialize the main window
        self.setObjectName('self')
        self.setWindowTitle('SMG - By Azeirah')
        self.resize(400, 250)

        # Gives the self an icon
        self.setWindowIcon(QIcon(resource_path('icon.png')))

        # create the tabs
        # the tab widget itself
        self.tabbed_windows = QTabWidget(self)
        self.tabbed_windows.resize(400, 300)

        # tab 1, contains the music player selection
        self.music_players = QFrame()

        # tab 2, contains options
        self.options = QFrame()
        self.tabbed_windows.addTab(self.music_players, 'Music players')
        self.tabbed_windows.addTab(self.options, 'Options')

        # initializes the two tabs, with all the code down below
        self.tab_music_players()
        self.tab_options()

        # shows the main window
        self.show()

        # self.update()
        CheckUpdateThread = Thread(target=self.update)
        CheckUpdateThread.setName('CheckUpdateThread')
        CheckUpdateThread.run()

    def closeEvent(self, event):
        """ an automatically called function when the program is about to
        close.
        """
        # Stops all Threads. These would continue to run in the background
        # Even if the window was closed.
        Main.running = False
        # close the ZuneNowPlaying.exe process
        if Constants.SUBP:
            Constants.SUBP.kill()

    def changeEvent(self, event):
        # if event.type() == QEvent.WindowStateChange:
        #     if self.isMinimized():
        #         event.ignore()
        #         self.hide()
        #         self.system_tray.showMessage('Running', 'Running in the
        #           background.')
        #         return

        super(UiMain, self).changeEvent(event)

    def on_systray_activated(self, reason):
        if reason == QSystemTrayIcon.DoubleClick:
            self.show()

    @staticmethod
    def toggle_split(event):
        # 0 = Qt.Unchecked The item is unchecked.
        # 1 = Qt.PartiallyChecked The item is partially checked. Items in
        # hierarchical models may be partially checked if some, but not all,
        # of
        # their children are checked.
        # 2 = Qt.Checked The item is checked.
        if event == 0:
            Constants.OPTIONS['splitText'] = False
        elif event == 2:
            Constants.OPTIONS['splitText'] = True

    def update(self):
        """ Checks a webpage for current version, compares this to built-in
        current versions, and shows update dialog if necessary
        """
        try:
            ver = urlopen('http://league-insanity.tk/Azeirah_content/version')\
                .read()
        except IOError:
            # if for some reason it couldn't retrieve the version, set it to
            # automatically ignore the update: False
            ver = False
        if not float(VERSION) >= float(ver):
            self.popup = QDialog(self)
            self.popup.setModal(True)
            self.popup.setGeometry(200, 100, 500, 100)
            self.popup.show()

            self.popup_text = QLabel(self.popup)
            self.popup_text.setGeometry(5, 5, 500, 30)
            self.popup_text.setOpenExternalLinks(True)
            self.popup_text.show()
            self.popup_text.setText(
                """There is an update available. Run update.exe or <a href='https://sourceforge.net/projects/obsmusicstreamd'>download the update manually</a>"""
            )
            # reply = QMessageBox.question(Constants.UI, 'Message',
            #                              "Do you want to update?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            # if reply == QMessageBox.Yes:
            #     import atexit
            #     import subprocess

            #     def runUpdater():
            #         import time
            #         time.sleep(3)
            #         subprocess.Popen(resource_path('update.exe'))
            #     atexit.register(runUpdater)
            #     sys.exit()

            #     Constants.update_dialog = QWidget()
            #     Constants.update_dialog.resize(350, 100)
            #     Constants.update_dialog.setWindowIcon(QIcon(resource_path\
            #         ('icon.png')))
            #     Constants.update_dialog.setWindowTitle('Updater')
            #     Constants.update_dialog_lbl = QLabel(Constants.update_dialog)
            #     Constants.update_dialog_lbl.setGeometry(10, 40, 340, 12)
            #     Constants.update_dialog.show()

            #     updateThread = Thread(target = update.update)
            #     updateThread.setName('updateThread')
            #     updateThread.start()

    def tab_music_players(self):
        """ Everything inside the Music players tab gets created here."""
        # self.music_players
        # Creates the box with all the music players inside of it
        self.app_select_box = QComboBox(self.music_players)
        self.app_select_box.setGeometry(135, 10, 150, 25)
        # Whenever you change the application, it runs the selectnewapp func
        self.app_select_box.activated[str].connect(self.select_new_app)

        # Creates the label for the selection combobox
        self.selector_lbl = QLabel(self.music_players)
        self.selector_lbl.setGeometry(10, 10, 150, 25)
        self.selector_lbl.setText('Select your music player: ')

        # Creates the label for the current playing song (and the current
        # playing song label)
        self.current_playing_lbl = QLabel(self.music_players)
        self.current_playing_lbl.setGeometry(10, 45, 150, 25)
        self.current_playing_lbl.setText('Current playing song: ')

        self.current_playing = QLabel(self.music_players)
        self.current_playing.setGeometry(117, 45, 250, 25)
        self.current_playing.setText(Misc.noSongPlaying)

        # Creates a label which displays any additional messages
        self.misc_messages = QLabel(self.music_players)
        self.misc_messages.setGeometry(10, 80, 390, 24)
        self.misc_messages.setText(Misc.misc_message())
        self.misc_messages.setOpenExternalLinks(True)

        # adds all the music players into the combobox
        self.app_select_box.addItem(None)
        for item in Constants.ACTIVEITEMS:
            if item == '__name__' or item == 'active':
                continue
            self.app_select_box.addItem(item)

        # creates the start button
        self.start_btn = QPushButton(self.music_players)
        self.start_btn.setGeometry(75, 120, 250, 35)
        self.start_btn.setText('Start')

        # links the start button to the self.start function
        QObject.connect(
            self.start_btn, SIGNAL("clicked()"),
            lambda: Thread(target=self.start, name='startbutton').start())

    def tab_options(self):
        """ Everything inside the Options tab gets created here. """
        # self.options

        # This section is for selecting output dir
        # Creates the output dir label
        self.output_dir_lbl = QLabel(self.options)
        self.output_dir_lbl.setGeometry(10, 10, 125, 15)
        self.output_dir_lbl.setText('Change Output Directory: ')

        # Creates the output dir button
        self.select_output_dir_btn = QPushButton(self.options)
        self.select_output_dir_btn.setGeometry(137, 8, 30, 20)
        self.select_output_dir_btn.setText('...')

        # Creates the output dir currentdir Lineedit
        self.output_cur_dir_lbl = QLineEdit(self.options)
        self.output_cur_dir_lbl.setGeometry(170, 6, 210, 25)
        self.output_cur_dir_lbl.setReadOnly(True)
        self.output_cur_dir_lbl.setText(
            Constants.CONFIG.get('directories', 'current_song'))

        # when the '...' button is clicked, show a dialog (fire func
        # disp_dialog)
        QObject.connect(self.select_output_dir_btn, SIGNAL("clicked()"),
                        self.disp_dialog)

        # This section is for selecting what players you use
        # The box with all the active players
        self.active_items_list = QListWidget(self.options)
        self.active_items_list.setGeometry(10, 40, 150, 100)

        # The box with all the inactive players
        self.inactive_items_list = QListWidget(self.options)
        self.inactive_items_list.setGeometry(230, 40, 150, 100)
        # Populate the two boxes with active and inactive items
        for item in Constants.ACTIVEITEMS:
            if item == '__name__' or item == 'active':
                continue
            self.active_items_list.addItem(item)
        for item in Constants.INACTIVEITEMS:
            if item == '__name__' or item == 'active':
                continue
            self.inactive_items_list.addItem(item)

        # The buttons responsible for switching
        # off button
        self.switch_active_item_button_off = QPushButton(self.options)
        self.switch_active_item_button_off.setText('->'.decode('utf-8'))
        # Makes the -> readable and clear
        self.switch_active_item_button_off.setFont(QFont('SansSerif', 17))
        self.switch_active_item_button_off.setGeometry(175, 55, 40, 30)
        # on button
        self.switch_active_item_button_on = QPushButton(self.options)
        self.switch_active_item_button_on.setText('<-'.decode('utf-8'))
        # makes <- readable and clear
        self.switch_active_item_button_on.setFont(QFont('SansSerif', 17))
        self.switch_active_item_button_on.setGeometry(175, 90, 40, 30)

        QObject.connect(self.switch_active_item_button_on, SIGNAL("clicked()"),
                        self.switch_item_on)
        QObject.connect(self.switch_active_item_button_off,
                        SIGNAL("clicked()"), self.switch_item_off)

        # A button to toggle the split output in half option. It's a temporary
        # fix for the Foobar double output problem.
        self.switch_output_split_btn = QCheckBox(self.options)
        self.switch_output_split_btn.setCheckState(Qt.CheckState.Unchecked)
        self.switch_output_split_btn.setGeometry(10, 140, 40, 30)
        self.switch_output_split_btn.stateChanged.connect(self.toggle_split)

        # The label for the split toggle
        self.switch_output_split_lbl = QLabel(self.options)
        self.switch_output_split_lbl.setText(
            "Split the output text in half (don't use this if you don't need it)"
        )
        self.switch_output_split_lbl.setGeometry(30, 140, 300, 30)

    def switch_item_on(self):
        """ Switches items (musicapps) on """
        try:
            # If an item from the active box is selected
            # Remove it and place it inside the inactive box
            item_taken = self.inactive_items_list.takeItem(
                self.inactive_items_list.currentRow())
            self.active_items_list.addItem(item_taken)
            active_items = {}
            inactive_items = {}
            for i in range(self.active_items_list.count()):
                active_items[self.active_items_list.item(i).text()] =\
                    ITEMS[self.active_items_list.item(i).text()
                          .encode('utf-8')]
            for i in range(self.inactive_items_list.count()):
                inactive_items[self.inactive_items_list.item(i).text()] =\
                    ITEMS[self.inactive_items_list.item(i).text()
                          .encode('utf-8')]
            Constants.ACTIVE_ITEMS = active_items
            Constants.INACTIVE_ITEMS = inactive_items
            # clear the selection combobox
            self.app_select_box.clear()
            # Repopulate the combobox
            self.app_select_box.addItem(None)
            for item in active_items:
                self.app_select_box.addItem(item)
            Constants.CONFIG.set('active', item_taken.text(),
                                 ITEMS[item_taken.text()])
            Constants.CONFIG.remove_option('inactive', item_taken.text())
            # Updates the config file to be up to date with activeItems
            Constants.CONFIG.update()
        except:
            raise

    def switch_item_off(self):
        """ Switches items (musicapps) off """
        try:
            # If an item from the inactive box is selected.
            # Remove it and place it inside the active box
            item_taken = self.active_items_list.takeItem(
                self.active_items_list.currentRow())
            self.inactive_items_list.addItem(item_taken)
            # update activeItems
            active_items = {}
            inactive_items = {}
            for i in range(self.active_items_list.count()):
                active_items[self.active_items_list.item(i).text()] =\
                    ITEMS[self.active_items_list.item(i).text()
                          .encode('utf-8')]
            for i in range(self.inactive_items_list.count()):
                inactive_items[self.inactive_items_list.item(i).text()] =\
                    ITEMS[self.inactive_items_list.item(i).text()
                          .encode('utf-8')]
            Constants.ACTIVE_ITEMS = active_items
            Constants.INACTIVE_ITEMS = inactive_items
            # clear the selection combobox
            self.app_select_box.clear()
            # Repopulate the combobox
            self.app_select_box.addItem(None)
            for item in active_items:
                self.app_select_box.addItem(item)
            # Updates the active items Constants property
            Constants.CONFIG.set('inactive', item_taken.text(),
                                 ITEMS[item_taken.text()])
            Constants.CONFIG.remove_option('active', item_taken.text())
            # Updates the config file to be up to date with activeItems
            Constants.CONFIG.update()
        except:
            raise

    def disp_dialog(self):
        """  displays the dialog which select a directory for output. """
        fname = QFileDialog.getExistingDirectory()
        Constants.CONFIG.set('directories', 'current_song', fname)
        self.output_cur_dir_lbl.setText(
            Constants.CONFIG.get('directories', 'current_song'))

    def select_new_app(self, text):
        """ Sets the new application to check for """
        try:
            Main.selectedProgram = ITEMS[text]
        except KeyError:
            # catches the empty option, it's obviously not in the dict
            pass
        # custom message for zune
        if Main.selectedProgram == 'zune':
            self.misc_messages.setText(Misc.ZuneNotification)
        # custom message for webplayers which require the groovemarklet
        elif text.find('*'):
            self.misc_messages.setText(Misc.GetGroovemarklet)

    def start(self):
        """ When the start button is pressed, start the main program loop """
        if Main.selectedProgram:
            if not Main.running:
                self.start_btn.setText('Stop')
                Main.running = True
                try:
                    pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
                except pythoncom.com_error:
                    # already initialized.
                    pass
                thread = Thread(target=Main.enumWindows, name='enumWindows')
                thread.run()
            else:
                self.start_btn.setText('Start')
                Main.running = False
                self.set_playing(Misc.noSongPlaying)
                Wr.write('')

    def set_playing(self, title=''):
        """ Sets the text of the label of what song is playing """
        # print 'setting title: ', title
        self.current_playing.setText(title)
Example #12
0
        myWindow.setIcon()

        myWindow.setButton()
        myWindow.setIconModes()
        myWindow.center()
        myWindow.setAboutButton()

        myWindow.show()
        myApp.exec_()
        sys.exit(0)
    except NameError:
        print("Name Error:", sys.exc_info()[1])
    except SystemExit:
        print("Closing Window...")
    except Exception:
        print(sys.exc_info()[1])
# Main Function
if __name__ == '__main2__':
    # Create the main application
    myApp = QApplication(sys.argv)
    # Create a Label and set its properties
    appLabel = QLabel()
    appLabel.setText("Hello, World!!!\n Look at my first app using PySide")
    appLabel.setAlignment(Qt.AlignCenter)
    appLabel.setWindowTitle("My First Application")
    appLabel.setGeometry(300, 300, 250, 175)
    # Show the Label
    appLabel.show()
    # Execute the Application and Exit
    myApp.exec_()
    sys.exit()
Example #13
0
class View(QWidget):
    """Base `View` class. Defines behavior common in all views"""
    # Selecting a good font family for each platform
    osname = platform.system()
    if osname == 'Windows':
        fontFamily = 'Segoe UI'
    elif osname == 'Linux':
        fontFamily = ''
    else:
        fontFamily = ''
    
    
    def __init__(self, parent=None):
        """
        Init method. Initializes parent classes
        
        :param parent: Reference to a `QWidget` object to be used as parent 
        """
        
        super(View, self).__init__(parent)
        
    @staticmethod
    def labelsFont():
        """Returns the `QFont` that `QLabels` should use"""   
        
        return View.font(True)
        
    @staticmethod
    def editsFont():
        """Returns the `QFont` that `QLineEdits` should use"""
        
        return View.font(False)
        
    @staticmethod
    def font(bold):
        """
        Returns a `QFont` object to be used in `View` derived classes.
        
        :param bold: Indicates whether or not the font will be bold
        """
        
        font = QFont(View.fontFamily, 9, 50, False)
        font.setBold(bold)
        
        return font
        
    def setLogo(self):
        """Sets the company logo in the same place in all views"""
        
        logoPixmap = QPixmap(':/resources/logo.png')
        self.iconLabel = QLabel(self)
        self.iconLabel.setPixmap(logoPixmap)
        self.iconLabel.setGeometry(20, 20, logoPixmap.width(), logoPixmap.height())
        
        self.linkLabel = QLabel(self)
        self.linkLabel.setText(
                """<font size="1"><a href="http://www.iqstorage.com/fromiqbox.php">
                Developed at IQ Storage FTP Hosing Services</a></font>""")
        self.linkLabel.setOpenExternalLinks(True)
        # Defines a visual line separator to be placed under the `logoPixmap` `QLabel`
        self.line = QFrame()
        self.line.setFrameShape(QFrame.HLine);
        self.line.setFrameShadow(QFrame.Sunken);
Example #14
0
class ImageBase(QLabel):
    def __init__(self, *args, **kwargs):

        self.transInfo = ImageBaseTranslateInfo()

        super(ImageBase, self).__init__(*args, **kwargs)
        self.installEventFilter(self)

        self.image = QImage()
        self.imageTransformed = QImage()
        self.pixmap = QPixmap()
        self.label = QLabel(self)
        self.imagePath = ""
        self.aspect = 1

    def loadImage(self, filePath):

        if self.imagePath == filePath: return None
        self.imagePath = filePath

        self.aspect = 1
        if self.image.load(filePath): pass
        self.resize()

    def resize(self):

        trValue = QTransform().scale(self.transInfo.scaleX(),
                                     self.transInfo.scaleY())
        trValue *= QTransform().rotate(self.transInfo.rotValue)
        imageTransformed = self.image.transformed(trValue)

        imageWidth = imageTransformed.width()
        imageHeight = imageTransformed.height()

        self.pixmap = QPixmap.fromImage(imageTransformed)
        self.label.setPixmap(self.pixmap)

        marginLeft = (self.width() - imageWidth) / 2.0
        marginTop = (self.height() - imageHeight) / 2.0

        self.label.setGeometry(marginLeft + self.transInfo.x,
                               marginTop + self.transInfo.y, imageWidth,
                               imageHeight)

    def flip(self, pressX):

        offsetX = pressX - self.width() / 2

        self.transInfo.rotValue *= -1
        self.transInfo.x = (self.transInfo.x - offsetX) * -1 + offsetX
        self.transInfo.scaleMultX *= -1

        self.resize()

    def show(self):
        self.label.show()

    def eventFilter(self, Obj, event):

        if event.type() == QtCore.QEvent.Resize:
            self.resize()
        elif event.type() == QtCore.QEvent.MouseButtonPress:
            pressX = event.x() - self.width() / 2
            pressY = event.y() - self.height() / 2
            self.transInfo.buttonPress(event.button(), pressX, pressY)
        elif event.type() == QtCore.QEvent.MouseButtonRelease:
            if self.transInfo.x == self.transInfo.bx and self.transInfo.y == self.transInfo.by:
                pass
            self.transInfo.buttonRelease()
            Window_global.saveInfo()
        elif event.type() == QtCore.QEvent.MouseMove:
            pressX = event.x() - self.width() / 2
            pressY = event.y() - self.height() / 2
            self.transInfo.drag(pressX, pressY)
            self.resize()
        elif event.type() == QtCore.QEvent.MouseButtonDblClick:
            self.flip(event.x())
        elif event.type() == QtCore.QEvent.Wheel:
            pressX = event.x() - self.width() / 2
            pressY = event.y() - self.height() / 2
            self.transInfo.buttonPress(QtCore.Qt.RightButton, pressX, pressY)
            self.transInfo.drag(pressX + event.delta() / 2, pressY)
            self.transInfo.buttonRelease()
            self.resize()
            Window_global.saveInfo()

        return True
Example #15
0
class LabelImage(QLabel):
    _pixmap = None
    _image = None
    _hide_icons = False
    _icon_size = 28

    download_started = Signal()
    download_ended = Signal()
    button_download_clicked = Signal()

    def __init__(self, parent=None):
        QLabel.__init__(self, parent)
        self.setText(self.tr("<u>can't obtain picture</u>"))

        self.lblLoadProcess = QLabel("...", self)
        self.lblLoadProcess.setMovie(QMovie(":/loading.gif"))
        self.lblLoadProcess.setAlignment(Qt.AlignCenter)
        self.lblLoadProcess.hide()

        self.btnDownload = QPushButton("", self)
        self.btnDownload.setIcon(QIcon(":/folder.png"))
        self.btnDownload.setIconSize(QSize(self._icon_size, self._icon_size))
        self.btnDownload.setFlat(True)
        self.btnDownload.clicked.connect(self.save_image)
        self.btnDownload.clicked.connect(self.button_download_clicked)

        self.download_ended.connect(self.check_image)
        self.download_ended.connect(self.lblLoadProcess.hide)
        self.download_ended.connect(self.btnDownload.show)
        self.download_ended.connect(self.end_load_anim)

        self.download_started.connect(self.start_load_anim)
        self.download_started.connect(self.btnDownload.hide)
        self.download_started.connect(self.lblLoadProcess.show)
        # self.destroyed.connect(self.on_destroyed)

    def start_load_anim(self):
        self.lblLoadProcess.movie().start()

    def end_load_anim(self):
        self.lblLoadProcess.movie().stop()

    @property
    def save_path(self):
        return os.path.join(config.save_dir, self._image.celeb.full_name, self._image.name)

    def save_image_thread_callback(self):
        self.download_started.emit()

        b = self._image.full_image_bytes
        path = self.save_path
        if not os.path.exists(os.path.dirname(path)):
            os.makedirs(os.path.dirname(path))

        img = Image.open(BytesIO(b))
        img.save(self.save_path)

        # f = open(path, 'w')
        # f.write(b)
        # f.close()
        try:
            self.download_ended.emit()
        except RuntimeError as e:
            log.debug(sys.exc_traceback)
            log.debug(sys.exc_info())

    def save_image(self):
        thread = Thread(target=self.save_image_thread_callback)
        thread.start()

    def check_image(self):
        if self._image:
            if os.path.exists(self.save_path):
                self.btnDownload.setIcon(QIcon(":/check.png"))
                return True
        self.btnDownload.setIcon(QIcon(":/folder.png"))
        return False

    def __setProp(self):
        if self._pixmap:
            QLabel.setPixmap(self, self._pixmap.scaled(
                self.width(), self.height(), Qt.KeepAspectRatio, Qt.SmoothTransformation))
        else:
            QLabel.setPixmap(self, QPixmap())

    @property
    def image(self):
        return self._image

    @image.setter
    def image(self, image):
        assert isinstance(image, ThePlaceImage)
        self._image = image
        path = os.path.abspath(image.icon_cache_path).replace('\\', '/')
        self.check_image()
        self.setPixmap(QPixmap(path))

    def setPixmap(self, px):
        self._pixmap = px
        self.__setProp()
        self.btnDownload.setVisible(not self.hide_icons and px is not None)

    def resizeEvent(self, *args, **kwargs):
        super(LabelImage, self).resizeEvent(*args, **kwargs)
        self.__setProp()

        self.btnDownload.move(self.width() - self.btnDownload.width() - 3,
                              self.height() - self.btnDownload.height() - 2)
        self.lblLoadProcess.setGeometry(self.btnDownload.geometry())

    @property
    def hide_icons(self):
        return self._hide_icons

    @hide_icons.setter
    def hide_icons(self, value):
        self._hide_icons = value
        self.btnDownload.setVisible(not self.hide_icons)
Example #16
0
class LoadingWidget(QWidget):
    """A widget with a little animation for showing progress.
    Call setMessage to change the secondary message and emit
    the finished signal with an appropriate string to set as the
    primary message when done.
  """
    finished = Signal(str)
    animation_finished = Signal()

    def __init__(self,
                 loadIcon="loading_bar",
                 primaryMessage="Please, Wait",
                 message='',
                 parent=None):
        super(LoadingWidget, self).__init__(parent)
        self.finished.connect(self._updateUI)
        self.setStyleSheet("""
      QWidget {
        background-color: #ffffff
      }
    """)
        self._icon_load = loadIcon
        self._primary_message = primaryMessage
        self._label_message = QLabel(message)
        self._label_message.setWordWrap(True)
        self._label_message.setAlignment(Qt.AlignCenter)
        self._label_primary_message = QLabel(self._primary_message)
        self._label_primary_message.setStyleSheet("""
      QLabel {
        font-size: 20px;
        font-weight:bold;
        color: rgb(65,65,65);
      }
    """)
        self._label_primary_message.setAlignment(Qt.AlignCenter)
        self._label_movie = QLabel()
        self._label_movie.setAlignment(Qt.AlignCenter)
        self._movie = QMovie(self._icon_load)
        self._label_movie.setMovie(self._movie)
        self._movie.start()
        layout = QVBoxLayout()
        layout.addWidget(self._label_primary_message)
        layout.addSpacing(5)
        layout.addWidget(self._label_message)
        layout.addSpacing(5)
        layout.addWidget(self._label_movie)
        layout.addStretch()
        #self._setupAnimation() # this should be done after showing everything to get correct geometries
        self.setLayout(layout)

    def _setupAnimation(self):
        self._load_animation = QPropertyAnimation(self._label_movie,
                                                  "geometry")
        # since the opacity is failing, make it run out of the area!
        anim_label_geom = self._label_movie.geometry()
        self._load_animation.setStartValue(anim_label_geom)
        target_anim_geom = QRect(anim_label_geom)
        target_anim_geom.moveTop(self.height())
        # make the animation target a rectangle that's directly under it but shifted downwards outside of parent
        self._load_animation.setEndValue(target_anim_geom)
        self._load_animation.setEasingCurve(QEasingCurve.InBack)
        self._load_animation.setDuration(1000)
        self._load_animation.finished.connect(self.animation_finished)
        self._load_animation.finished.connect(self._hideAnimLabel)

    def setMessage(self, message):
        self._label_message.setText(message)

    def _updateUI(self, message=''):
        if not message:
            message = "All Done!"
        self._label_primary_message.setText(message)
        self._label_message.setText('')
        self._movie.stop()
        self._setupAnimation()
        self.layout().removeWidget(self._label_movie)
        self._label_movie.setGeometry(self._load_animation.startValue())
        self._load_animation.start()

    def _hideAnimLabel(self):
        self._label_movie.hide()
Example #17
0
import sys
from PySide.QtCore import Qt
from PySide.QtGui import QApplication, QLabel

# Main Function
if __name__ == '__main__':

    # Create the main application
    myApp = QApplication(sys.argv)

    # Create a label and set its properties
    appLabel = QLabel()
    appLabel.setText("Hello World \n Look at my first app using PySide")
    appLabel.setAlignment(Qt.AlignCenter)
    appLabel.setWindowTitle("My first application")
    appLabel.setGeometry(300, 300, 250, 150)

    # Show the label
    appLabel.show()

    # Execute the application and exit
    myApp.exec_()
    sys.exit
Example #18
0
class Ui_MainWindow(object):
    
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.setFixedSize(800, 600)
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.FilterLbl = QLabel(self.centralwidget)
        self.FilterLbl.setGeometry(QtCore.QRect(30, 150, 60, 15))
        self.FilterLbl.setObjectName("FilterLbl")
        self.FilterCB = QComboBox(self.centralwidget)
        self.FilterCB.setGeometry(QtCore.QRect(450, 150, 100, 22))
        self.FilterCB.setObjectName("FilterCB")
        self.FilterCB.addItem("")
        self.FilterCB.addItem("")
        self.FilterCB.addItem("")
        self.FilterCB.addItem("")         
        self.FilterTF = QLineEdit(self.centralwidget)
        self.FilterTF.setGeometry(QtCore.QRect(100, 150, 320, 20))        
        self.tableView = QTableWidget(self.centralwidget)
        self.tableView.setGeometry(QtCore.QRect(10, 180, 781, 511))
        self.tableView.setObjectName("tableView")
        self.tableView.setColumnCount(4)
        self.tableView.setRowCount(0)
        item = QTableWidgetItem("Cena za kg/l")
        self.tableView.setHorizontalHeaderItem(0, item)
        item = QTableWidgetItem("Cena ze kus")
        self.tableView.setHorizontalHeaderItem(1, item)
        item = QTableWidgetItem(u"Gramaž")
        self.tableView.setHorizontalHeaderItem(2, item)
        item = QTableWidgetItem("Popis")
        item.setTextAlignment(QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter|QtCore.Qt.AlignCenter)
        font = QtGui.QFont()
        font.setPointSize(8)
        item.setFont(font)
        self.tableView.setHorizontalHeaderItem(3, item)
        self.tableView.horizontalHeader().setStretchLastSection(True)
        
        self.SaveBtn = QPushButton(self.centralwidget)
        self.SaveBtn.setGeometry(QtCore.QRect(30, 10, 100, 23))
        self.SaveBtn.setObjectName("SaveBtn")
        self.PrintSelectedToFileBtn = QPushButton(self.centralwidget)
        self.PrintSelectedToFileBtn.setGeometry(QtCore.QRect(225, 10, 100, 23))        
        self.PrintSelectedToFileBtn.setObjectName("PrintSelectedToFileBtn")
        self.PriceForUnitTF = QLineEdit(self.centralwidget)
        self.PriceForUnitTF.setGeometry(QtCore.QRect(100, 70, 113, 20))
        self.PriceForUnitTF.setObjectName("PriceForUnitTF")
        self.PriceForUnitLbl = QLabel(self.centralwidget)
        self.PriceForUnitLbl.setGeometry(QtCore.QRect(30, 70, 60, 13))
        self.PriceForUnitLbl.setObjectName("PriceForUnitLbl")
        self.ArtikelTF = QLineEdit(self.centralwidget)
        self.ArtikelTF.setGeometry(QtCore.QRect(100, 100, 113, 20))
        self.ArtikelTF.setObjectName("ArtikelTF")
        self.ArtikelLbl = QLabel(self.centralwidget)
        self.ArtikelLbl.setGeometry(QtCore.QRect(30, 100, 46, 13))
        self.ArtikelLbl.setObjectName("ArtikelLbl")
        self.DescriptionLbl = QLabel(self.centralwidget)
        self.DescriptionLbl.setGeometry(QtCore.QRect(455, 70, 75, 13))
        self.DescriptionLbl.setObjectName("DescriptionLbl")
        self.UnitLbl = QLabel(self.centralwidget)
        self.UnitLbl.setGeometry(QtCore.QRect(250, 70, 60, 15))
        self.UnitLbl.setObjectName("UnitLbl")
        self.WeightLbl = QLabel(self.centralwidget)
        self.WeightLbl.setGeometry(QtCore.QRect(250, 100, 60, 13))
        self.WeightLbl.setObjectName("UnitLbl")
        self.WeightTF = QLineEdit(self.centralwidget)
        self.WeightTF.setGeometry(QtCore.QRect(320, 100, 100, 20))
        self.WeightTF.setObjectName("WeightTF")        
        self.UnitCB = QComboBox(self.centralwidget)
        self.UnitCB.setGeometry(QtCore.QRect(320, 70, 100, 22))
        self.UnitCB.setObjectName("UnitCB")
        self.UnitCB.addItem("")
        self.UnitCB.addItem("")
        self.DescriptionTE = QPlainTextEdit(self.centralwidget)
        self.DescriptionTE.setGeometry(QtCore.QRect(540, 30, 241, 61))
        self.DescriptionTE.setObjectName("DescriptionTE")
        self.PrintToFileBtn = QPushButton(self.centralwidget)
        self.PrintToFileBtn.setGeometry(QtCore.QRect(140, 10, 75, 23))
        self.PrintToFileBtn.setObjectName("PrintToFileBtn")
        self.AddRecordBtn = QPushButton(self.centralwidget)
        self.AddRecordBtn.setGeometry(QtCore.QRect(450, 100, 75, 23))
        self.AddRecordBtn.setObjectName("AddRecordBtn")        
        self.SaveChangeBtn = QPushButton(self.centralwidget)
        self.SaveChangeBtn.setGeometry(QtCore.QRect(550, 100, 75, 23))
        self.SaveChangeBtn.setObjectName("SaveChangeBtn")
        self.DeleteRecordBtn = QPushButton(self.centralwidget)
        self.DeleteRecordBtn.setGeometry(QtCore.QRect(650, 100, 75, 23))
        self.DeleteRecordBtn.setObjectName("DeleteRecordBtn")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
   
        self.FilterTF.textChanged.connect(self.on_lineEdit_textChanged)
        self.FilterCB.currentIndexChanged.connect(self.on_comboBox_currentIndexChanged)
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def myFilter(self,col=None):
        filt = self.FilterTF.text()
        for ix in range(self.tableView.rowCount()):
            match = False
            if col == None:
                for jx in range(self.tableView.columnCount()):
                    item = self.tableView.item(ix,jx)
                    if filt in item.text():
                        match = True
                        break
                self.tableView.setRowHidden(ix, not match)
            else:
                item = self.tableView.item(ix, col)
                if filt in item.text():
                    match = True
                self.tableView.setRowHidden(ix, not match)

    #@QtCore.pyqtSlot(str)
    def on_lineEdit_textChanged(self, text):
        self.myFilter()

    #@QtCore.pyqtSlot(int)
    def on_comboBox_currentIndexChanged(self, index):
        self.myFilter(col=index)
        
    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Stitky - {0}".format(__version__)))
        self.SaveBtn.setText(_translate("MainWindow", "Uloz stav tabulky"))
        self.PrintSelectedToFileBtn.setText(_translate("MainWindow", "Tisk vybranych"))
        self.PriceForUnitLbl.setText(_translate("MainWindow", "Cena za kus:"))
        self.ArtikelLbl.setText(_translate("MainWindow", "Artikl:"))
        self.DescriptionLbl.setText(_translate("MainWindow", "Popis produktu:"))
        self.UnitLbl.setText(_translate("MainWindow", "Jednotka:"))
        self.FilterLbl.setText(_translate("MainWindow", "Filtr:"))
        self.WeightLbl.setText(_translate("MainWindow", "Hmotnost:"))
        self.PrintToFileBtn.setText(_translate("MainWindow", "Vytvor txt"))
        self.SaveChangeBtn.setText(_translate("MainWindow", "Uloz zmeny"))
        self.AddRecordBtn.setText(_translate("MainWindow", "Pridej zaznam"))
        self.DeleteRecordBtn.setText(_translate("MainWindow", "Smaz zaznam"))
        self.UnitCB.setItemText(0, _translate("MainWindow", "g"))
        self.UnitCB.setItemText(1, _translate("MainWindow", "ml"))
        self.FilterCB.setItemText(0, _translate("MainWindow", "Cena za kg/l"))
        self.FilterCB.setItemText(1, _translate("MainWindow", "Cena ze kus"))
        self.FilterCB.setItemText(2, _translate("MainWindow", "Gramaz"))
        self.FilterCB.setItemText(3, _translate("MainWindow", "Popis"))
Example #19
0
File: guiv2.py Project: dylziez/SMG
class UiMain(QMainWindow):

    """ The main gui interface, invokes all windows and ties everything
     together
    """

    def __init__(self):
        """ automatically called __init__ function """

        super(UiMain, self).__init__()

        # initialize all the variables that are going to be defined in the
        # future
        self.update_dialog = None
        self.update_dialog_lbl = None
        self.app_select_box = None
        self.selector_lbl = None
        self.current_playing_lbl = None
        self.current_playing = None
        self.misc_messages = None
        self.start_btn = None
        self.output_dir_lbl = None
        self.select_output_dir_btn = None
        self.output_cur_dir_lbl = None
        self.active_items_list = None
        self.inactive_items_list = None
        self.switch_active_item_button_off = None
        self.switch_active_item_button_on = None
        self.switch_output_split_btn = None
        self.switch_output_split_lbl = None

        # initialize the system tray
        # self.system_tray = QSystemTrayIcon(self)
        # self.system_tray.setIcon(QIcon(resource_path('icon.png')))
        # self.system_tray.show()
        # self.system_tray.setToolTip('SMG')
        # self.system_tray.activated.connect(self.on_systray_activated)

        # initialize the main window
        self.setObjectName('self')
        self.setWindowTitle('SMG - By Azeirah')
        self.resize(400, 250)

        # Gives the self an icon
        self.setWindowIcon(QIcon(resource_path('icon.png')))

        # create the tabs
        # the tab widget itself
        self.tabbed_windows = QTabWidget(self)
        self.tabbed_windows.resize(400, 300)

        # tab 1, contains the music player selection
        self.music_players = QFrame()

        # tab 2, contains options
        self.options = QFrame()
        self.tabbed_windows.addTab(self.music_players, 'Music players')
        self.tabbed_windows.addTab(self.options, 'Options')

        # initializes the two tabs, with all the code down below
        self.tab_music_players()
        self.tab_options()

        # shows the main window
        self.show()
        
    def closeEvent(self, event):
        """ an automatically called function when the program is about to
        close.
        """
        # Stops all Threads. These would continue to run in the background
        # Even if the window was closed.
        Main.running = False
        # close the ZuneNowPlaying.exe process
        if Constants.SUBP:
            Constants.SUBP.kill()

    def changeEvent(self, event):
        # if event.type() == QEvent.WindowStateChange:
        #     if self.isMinimized():
        #         event.ignore()
        #         self.hide()
        #         self.system_tray.showMessage('Running', 'Running in the
        #           background.')
        #         return

        super(UiMain, self).changeEvent(event)

    def on_systray_activated(self, reason):
        if reason == QSystemTrayIcon.DoubleClick:
            self.show()

    @staticmethod
    def toggle_split(event):
        # 0 = Qt.Unchecked The item is unchecked.
        # 1 = Qt.PartiallyChecked The item is partially checked. Items in
        # hierarchical models may be partially checked if some, but not all,
        # of
        # their children are checked.
        # 2 = Qt.Checked The item is checked.
        if event == 0:
            Constants.OPTIONS['splitText'] = False
        elif event == 2:
            Constants.OPTIONS['splitText'] = True

    def update(self):
        """ Checks a webpage for current version, compares this to built-in
        current versions, and shows update dialog if necessary
        """
        try:
            ver = urlopen('http://league-insanity.tk/Azeirah_content/version')\
                .read()
        except IOError:
            # if for some reason it couldn't retrieve the version, set it to
            # automatically ignore the update: False
            ver = False
        if not float(VERSION) >= float(ver):
            self.popup = QDialog(self)
            self.popup.setModal(True)
            self.popup.setGeometry(200, 100, 500, 100)
            self.popup.show()

            self.popup_text = QLabel(self.popup)
            self.popup_text.setGeometry(5, 5, 500, 30)
            self.popup_text.setOpenExternalLinks(True)
            self.popup_text.show()
            self.popup_text.setText(
                """There is an update available. Run update.exe or <a href='https://sourceforge.net/projects/obsmusicstreamd'>download the update manually</a>""")
            # reply = QMessageBox.question(Constants.UI, 'Message',
            #                              "Do you want to update?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            # if reply == QMessageBox.Yes:
            #     import atexit
            #     import subprocess

            #     def runUpdater():
            #         import time
            #         time.sleep(3)
            #         subprocess.Popen(resource_path('update.exe'))
            #     atexit.register(runUpdater)
            #     sys.exit()

            #     Constants.update_dialog = QWidget()
            #     Constants.update_dialog.resize(350, 100)
            #     Constants.update_dialog.setWindowIcon(QIcon(resource_path\
            #         ('icon.png')))
            #     Constants.update_dialog.setWindowTitle('Updater')
            #     Constants.update_dialog_lbl = QLabel(Constants.update_dialog)
            #     Constants.update_dialog_lbl.setGeometry(10, 40, 340, 12)
            #     Constants.update_dialog.show()

            #     updateThread = Thread(target = update.update)
            #     updateThread.setName('updateThread')
            #     updateThread.start()

    def tab_music_players(self):
        """ Everything inside the Music players tab gets created here."""
        # self.music_players
        # Creates the box with all the music players inside of it
        self.app_select_box = QComboBox(self.music_players)
        self.app_select_box.setGeometry(135, 10, 150, 25)
        # Whenever you change the application, it runs the selectnewapp func
        self.app_select_box.activated[str].connect(self.select_new_app)

        # Creates the label for the selection combobox
        self.selector_lbl = QLabel(self.music_players)
        self.selector_lbl.setGeometry(10, 10, 150, 25)
        self.selector_lbl.setText('Select your music player: ')

        # Creates the label for the current playing song (and the current
        # playing song label)
        self.current_playing_lbl = QLabel(self.music_players)
        self.current_playing_lbl.setGeometry(10, 45, 150, 25)
        self.current_playing_lbl.setText('Current playing song: ')

        self.current_playing = QLabel(self.music_players)
        self.current_playing.setGeometry(117, 45, 250, 25)
        self.current_playing.setText(Misc.noSongPlaying)

        # Creates a label which displays any additional messages
        self.misc_messages = QLabel(self.music_players)
        self.misc_messages.setGeometry(10, 80, 390, 24)
        self.misc_messages.setText(Misc.misc_message())
        self.misc_messages.setOpenExternalLinks(True)

        # adds all the music players into the combobox
        self.app_select_box.addItem(None)
        for item in Constants.ACTIVEITEMS:
            if item == '__name__' or item == 'active':
                continue
            self.app_select_box.addItem(item)

        # creates the start button
        self.start_btn = QPushButton(self.music_players)
        self.start_btn.setGeometry(75, 120, 250, 35)
        self.start_btn.setText('Start')

        # links the start button to the self.start function
        QObject.connect(self.start_btn, SIGNAL("clicked()"),
                        lambda: Thread(target=self.start, name='startbutton').start())

    def tab_options(self):
        """ Everything inside the Options tab gets created here. """
        # self.options

        # This section is for selecting output dir
        # Creates the output dir label
        self.output_dir_lbl = QLabel(self.options)
        self.output_dir_lbl.setGeometry(10, 10, 125, 15)
        self.output_dir_lbl.setText('Change Output Directory: ')

        # Creates the output dir button
        self.select_output_dir_btn = QPushButton(self.options)
        self.select_output_dir_btn.setGeometry(137, 8, 30, 20)
        self.select_output_dir_btn.setText('...')

        # Creates the output dir currentdir Lineedit
        self.output_cur_dir_lbl = QLineEdit(self.options)
        self.output_cur_dir_lbl.setGeometry(170, 6, 210, 25)
        self.output_cur_dir_lbl.setReadOnly(True)
        self.output_cur_dir_lbl.setText(Constants.CONFIG.
                                        get('directories', 'current_song'))

        # when the '...' button is clicked, show a dialog (fire func
        # disp_dialog)
        QObject.connect(self.select_output_dir_btn, SIGNAL("clicked()"),
                        self.disp_dialog)

        # This section is for selecting what players you use
        # The box with all the active players
        self.active_items_list = QListWidget(self.options)
        self.active_items_list.setGeometry(10, 40, 150, 100)

        # The box with all the inactive players
        self.inactive_items_list = QListWidget(self.options)
        self.inactive_items_list.setGeometry(230, 40, 150, 100)
        # Populate the two boxes with active and inactive items
        for item in Constants.ACTIVEITEMS:
            if item == '__name__' or item == 'active':
                continue
            self.active_items_list.addItem(item)
        for item in Constants.INACTIVEITEMS:
            if item == '__name__' or item == 'active':
                continue
            self.inactive_items_list.addItem(item)

        # The buttons responsible for switching
        # off button
        self.switch_active_item_button_off = QPushButton(self.options)
        self.switch_active_item_button_off.setText('->'.decode('utf-8'))
        # Makes the -> readable and clear
        self.switch_active_item_button_off.setFont(QFont('SansSerif', 17))
        self.switch_active_item_button_off.setGeometry(175, 55, 40, 30)
        # on button
        self.switch_active_item_button_on = QPushButton(self.options)
        self.switch_active_item_button_on.setText('<-'.decode('utf-8'))
        # makes <- readable and clear
        self.switch_active_item_button_on.setFont(QFont('SansSerif', 17))
        self.switch_active_item_button_on.setGeometry(175, 90, 40, 30)

        QObject.connect(self.switch_active_item_button_on, SIGNAL
                       ("clicked()"), self.switch_item_on)
        QObject.connect(self.switch_active_item_button_off, SIGNAL
                       ("clicked()"), self.switch_item_off)

        # A button to toggle the split output in half option. It's a temporary
        # fix for the Foobar double output problem.
        self.switch_output_split_btn = QCheckBox(self.options)
        self.switch_output_split_btn.setCheckState(Qt.CheckState.Unchecked)
        self.switch_output_split_btn.setGeometry(10, 140, 40, 30)
        self.switch_output_split_btn.stateChanged.connect(self.toggle_split)

        # The label for the split toggle
        self.switch_output_split_lbl = QLabel(self.options)
        self.switch_output_split_lbl.setText(
            "Split the output text in half (don't use this if you don't need it)")
        self.switch_output_split_lbl.setGeometry(30, 140, 300, 30)

    def switch_item_on(self):
        """ Switches items (musicapps) on """
        try:
            # If an item from the active box is selected
            # Remove it and place it inside the inactive box
            item_taken = self.inactive_items_list.takeItem(
                self.inactive_items_list.currentRow())
            self.active_items_list.addItem(item_taken)
            active_items = {}
            inactive_items = {}
            for i in range(self.active_items_list.count()):
                active_items[self.active_items_list.item(i).text()] =\
                    ITEMS[self.active_items_list.item(i).text()
                          .encode('utf-8')]
            for i in range(self.inactive_items_list.count()):
                inactive_items[self.inactive_items_list.item(i).text()] =\
                    ITEMS[self.inactive_items_list.item(i).text()
                          .encode('utf-8')]
            Constants.ACTIVE_ITEMS = active_items
            Constants.INACTIVE_ITEMS = inactive_items
            # clear the selection combobox
            self.app_select_box.clear()
            # Repopulate the combobox
            self.app_select_box.addItem(None)
            for item in active_items:
                self.app_select_box.addItem(item)
            Constants.CONFIG.set('active', item_taken.text(),
                                 ITEMS[item_taken.text()])
            Constants.CONFIG.remove_option('inactive', item_taken.text())
            # Updates the config file to be up to date with activeItems
            Constants.CONFIG.update()
        except:
            raise

    def switch_item_off(self):
        """ Switches items (musicapps) off """
        try:
            # If an item from the inactive box is selected.
            # Remove it and place it inside the active box
            item_taken = self.active_items_list.takeItem(
                self.active_items_list.currentRow())
            self.inactive_items_list.addItem(item_taken)
            # update activeItems
            active_items = {}
            inactive_items = {}
            for i in range(self.active_items_list.count()):
                active_items[self.active_items_list.item(i).text()] =\
                    ITEMS[self.active_items_list.item(i).text()
                          .encode('utf-8')]
            for i in range(self.inactive_items_list.count()):
                inactive_items[self.inactive_items_list.item(i).text()] =\
                    ITEMS[self.inactive_items_list.item(i).text()
                          .encode('utf-8')]
            Constants.ACTIVE_ITEMS = active_items
            Constants.INACTIVE_ITEMS = inactive_items
            # clear the selection combobox
            self.app_select_box.clear()
            # Repopulate the combobox
            self.app_select_box.addItem(None)
            for item in active_items:
                self.app_select_box.addItem(item)
            # Updates the active items Constants property
            Constants.CONFIG.set('inactive', item_taken.text(),
                                 ITEMS[item_taken.text()])
            Constants.CONFIG.remove_option('active', item_taken.text())
            # Updates the config file to be up to date with activeItems
            Constants.CONFIG.update()
        except:
            raise

    def disp_dialog(self):
        """  displays the dialog which select a directory for output. """
        fname = QFileDialog.getExistingDirectory()
        Constants.CONFIG.set('directories', 'current_song', fname)
        self.output_cur_dir_lbl.setText(Constants.CONFIG.
                                        get('directories', 'current_song'))

    def select_new_app(self, text):
        """ Sets the new application to check for """
        try:
            Main.selectedProgram = ITEMS[text]
        except KeyError:
            # catches the empty option, it's obviously not in the dict
            pass
        # custom message for zune
        if Main.selectedProgram == 'zune':
            self.misc_messages.setText(Misc.ZuneNotification)
        # custom message for webplayers which require the groovemarklet
        elif text.find('*'):
            self.misc_messages.setText(Misc.GetGroovemarklet)

    def start(self):
        """ When the start button is pressed, start the main program loop """
        if Main.selectedProgram:
            if not Main.running:
                self.start_btn.setText('Stop')
                Main.running = True
                try:
                    pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
                except pythoncom.com_error:
                    # already initialized.
                    pass
                thread = Thread(
                    target=Main.enumWindows, name='enumWindows')
                thread.run()
            else:
                self.start_btn.setText('Start')
                Main.running = False
                self.set_playing(Misc.noSongPlaying)
                Wr.write('')

    def set_playing(self, title=''):
        """ Sets the text of the label of what song is playing """
        # print 'setting title: ', title
        self.current_playing.setText(title)
Example #20
0
class TransformationFaceUI(QWidget):
    def __init__(self, oriPath, protoPath, oriPointsPath, protoPointsPath,
                 regionsPath):
        super(TransformationFaceUI, self).__init__()
        #Initialize the data or object we need

        localParas, points = preprocess(oriPath, protoPath, oriPointsPath,
                                        protoPointsPath, regionsPath, 'L2')
        self.oriImg, self.protoImg, self.regionsPoints, self.is_in_regions_fun, self.distance_funs, self.affine_funs = localParas
        self.oriPlotDict, self.protoPlotDict, self.oriPoints, self.protoPoints = points
        self.oriPoints = np.array(self.oriPoints)
        self.protoPoints = np.array(self.protoPoints)
        self.e = 2
        self.alpha = 1
        self.oriPath = oriPath
        self.protoPath = protoPath
        self.oriPointsPath = oriPointsPath
        self.protoPointsPath = protoPointsPath
        self.regionsPath = regionsPath
        self.transform = 'Local Affine Transformation'
        self.newImg = None
        self.initUI()

    def initUI(self):
        QToolTip.setFont(QFont('SansSerif', 10))
        self.setGeometry(300, 200, 810, 430)
        self.setWindowTitle('Transformation on Human Face')

        #Method choose combobox
        self.comboAffineLabel = QLabel(self)
        self.comboAffineLabel.setText('Transformation Method:')
        self.comboAffineLabel.setGeometry(60, 270, 230, 30)

        self.comboAffine = QComboBox(self)
        self.comboAffine.addItem("Local Affine Transformation")
        self.comboAffine.addItem("Moving Least Squares")
        self.comboAffine.addItem("Morphing")
        self.comboAffine.setGeometry(22, 290, 225, 30)
        self.comboAffine.activated[str].connect(self.affineChoiceChange)

        #The button to choose the original figure
        self.oriBtn = QPushButton('Choose Original Picture', self)
        self.oriBtn.setToolTip('Choose Original Picture')
        self.oriBtn.setGeometry(20, 330, 230, 30)
        self.oriBtn.clicked.connect(self.showOriDialog)

        #The button to choose the proto figure
        self.protoBtn = QPushButton('Choose Proto Picture', self)
        self.protoBtn.setToolTip('Choose Proto Picture')
        self.protoBtn.setGeometry(20, 365, 230, 30)
        self.protoBtn.clicked.connect(self.showProtoDialog)

        #The distance function choose combobox
        self.comboLabel = QLabel(self)
        self.comboLabel.setText('Distance Fun:')
        self.comboLabel.setGeometry(310, 280, 200, 30)

        self.comboDis = QComboBox(self)
        self.comboDis.addItem("L2")
        self.comboDis.addItem("L1")
        self.comboDis.setGeometry(410, 280, 80, 30)

        self.comboDis.activated[str].connect(self.distanceChoiceChange)

        #E choose slider

        self.eLabel = QLabel(self)
        self.eLabel.setText('E Value:0.00')
        self.eLabel.setGeometry(310, 320, 200, 30)
        self.eSld = QSlider(Qt.Horizontal, self)
        self.eSld.setRange(0, 10**5)
        self.eSld.setFocusPolicy(Qt.NoFocus)
        self.eSld.setGeometry(390, 320, 120, 30)
        self.eSld.valueChanged[int].connect(self.changeEValue)

        #alpha choose slider
        self.aLabel = QLabel(self)
        self.aLabel.setText('Alpha Value:0.00')
        self.aLabel.setGeometry(310, 360, 200, 30)
        self.aSld = QSlider(Qt.Horizontal, self)
        self.aSld.setRange(0, 10**5)
        self.aSld.setFocusPolicy(Qt.NoFocus)
        self.aSld.setGeometry(410, 360, 100, 30)
        self.aSld.valueChanged[int].connect(self.changeAlphaValue)

        # Picture show
        self.oriTextLabel = QLabel(self)
        self.protoTextLabel = QLabel(self)
        self.transTextLabel = QLabel(self)
        self.oriTextLabel.setText('The Orginal Picture')
        self.protoTextLabel.setText('The Proto Picture')
        self.transTextLabel.setText('The Picture after Transformation')

        self.oriTextLabel.move(70, 5)
        self.protoTextLabel.move(350, 5)
        self.transTextLabel.move(580, 5)

        self.oriLabel = QLabel(self)
        self.protoLabel = QLabel(self)
        self.transLabel = QLabel(self)

        pixmap = QPixmap(self.oriPath)
        pixmap2 = QPixmap(self.protoPath)
        self.oriLabel.setPixmap(pixmap)
        self.protoLabel.setPixmap(pixmap2)
        self.transLabel.setPixmap(pixmap)

        #Position setting
        self.oriLabel.setGeometry(20, 20, 230, 230)
        self.protoLabel.setGeometry(290, 20, 230, 230)
        self.transLabel.setGeometry(560, 20, 230, 230)
        self.oriLabel.setScaledContents(True)
        self.protoLabel.setScaledContents(True)
        self.transLabel.setScaledContents(True)
        #Load button
        self.loadOriBtn = QPushButton('Load Ori Points', self)
        self.loadOriBtn.setToolTip('Load Control Points From Txt File')
        self.loadOriBtn.setGeometry(550, 280, 130, 30)
        self.loadOriBtn.clicked.connect(self.showLoadOriDialog)

        self.loadProtoBtn = QPushButton('Load Proto Points', self)
        self.loadProtoBtn.setToolTip('Load Control Points From Txt File')
        self.loadProtoBtn.setGeometry(680, 280, 130, 30)
        self.loadProtoBtn.clicked.connect(self.showLoadProtoDialog)
        #Face ++ button
        self.faceBtn = QPushButton('Face++ Keypoint', self)
        self.faceBtn.setToolTip('Save the Face++ Keypoints')
        self.faceBtn.setGeometry(550, 315, 130, 30)
        self.faceBtn.clicked.connect(self.detectKeyPoints)
        #Load region Button
        self.loadRegionBtn = QPushButton('Load Regions', self)
        self.loadRegionBtn.setToolTip('Load Regions From Txt File')
        self.loadRegionBtn.setGeometry(680, 315, 130, 30)
        self.loadRegionBtn.clicked.connect(self.showLoadRegionDialog)

        #Save Button setting
        self.saveBtn = QPushButton('Save', self)
        self.saveBtn.setToolTip(
            'Transform this picture to the shape of Baboon')
        self.saveBtn.setGeometry(560, 350, 110, 40)
        self.saveBtn.clicked.connect(self.saveImg)

        #Transform action button
        self.confirmBtn = QPushButton('Generate', self)
        self.confirmBtn.setToolTip('Generate')
        self.confirmBtn.setGeometry(680, 350, 110, 40)
        self.confirmBtn.clicked.connect(self.transformAction)

        self.show()

    #Invoke face++ and save which is connected to the facebtn
    def detectKeyPoints(self):
        print(self.oriPath)
        save_points('face_keypoints_ori.txt',
                    detect((self.oriPath).encode('utf-8')))

    #Save img connected to the save button
    def saveImg(self):
        if self.newImg == None:
            QtGui.QMessageBox.information(self, "Error",
                                          "There is not transformed figure")
        result = Image.fromarray(self.newImg)
        filenames = self.oriPath.split('/')
        filenames[len(filenames) -
                  1] = 'trans_' + filenames[len(filenames) - 1]
        newPath = '/'.join(filenames)
        result.save(newPath)

    #Connected to the transform button did the deformation and show it
    def transformAction(self):

        try:
            #For different methods have different solution
            if self.transform == 'Morphing':
                self.oriImg = np.array(Image.open(self.oriPath))
                self.protoImg = np.array(Image.open(self.protoPath))
                if self.oriImg.shape != self.protoImg.shape:
                    QtGui.QMessageBox.information(
                        self, "Error",
                        "It is image morphing and required the same size of two images,please choose other images"
                    )
                    return
                newImg = morphingAction((self.oriPath).encode('utf-8'),
                                        self.protoPath.encode('utf-8'),
                                        self.protoPointsPath.encode('utf-8'),
                                        self.alpha)
            else:
                localParas, points = preprocess(self.oriPath, self.protoPath,
                                                self.oriPointsPath,
                                                self.protoPointsPath,
                                                self.regionsPath, 'L2')
                if points == None:
                    QtGui.QMessageBox.information(self, "Error", localParas)
                    return
                self.oriImg, self.protoImg, self.regionsPoints, self.is_in_regions_fun, self.distance_funs, self.affine_funs = localParas
                self.oriPlotDict, self.protoPlotDict, self.oriPoints, self.protoPoints = points
                if self.oriImg.shape[len(self.oriImg.shape) -
                                     1] != self.protoImg.shape[
                                         len(self.protoImg.shape) - 1]:
                    QtGui.QMessageBox.information(
                        self, "Error",
                        "The type of the figures is not the same, please choose another figure"
                    )
                    return
                if self.transform == 'Local Affine Transformation':
                    newImg = local_affine_transformation(
                        self.oriImg, self.protoImg, self.e, self.regionsPoints,
                        self.is_in_regions_fun, self.distance_funs,
                        self.affine_funs)
                elif self.transform == "Moving Least Squares":
                    newImg = affine_points_MLS(self.oriImg, self.protoImg,
                                               self.oriPoints,
                                               self.protoPoints, self.alpha)
        except BaseException:

            QtGui.QMessageBox.information(
                self, "Error",
                "There are error in the point choice or other things.")
            newImg = morphingAction((self.oriPath).encode('utf-8'),
                                    self.protoPath.encode('utf-8'),
                                    self.protoPointsPath.encode('utf-8'),
                                    self.alpha)

        self.newImg = np.uint8(newImg)
        newImg = rgb2bgr(np.uint8(newImg))

        qimage = QImage(newImg, newImg.shape[1], newImg.shape[0],
                        QImage.Format_ARGB32)
        pixmap_array = QPixmap.fromImage(qimage)
        self.transLabel.setPixmap(pixmap_array)
################################################################################################
################################################################################################
################################################################################################
################################################################################################
################################################################################################
################################################################################################
################################################################################################
################################################################################################

#The file chooser , all of the function begin with show is the same but for different parameter.

    def showProtoDialog(self):

        fname, _ = QtGui.QFileDialog.getOpenFileName(
            self, 'Open file', '/home', "Image Files (*.png *.jpg *.bmp)")
        if fname != None and fname != '':
            self.protoPath = fname
            self.protoLabel.setPixmap(QPixmap(self.protoPath))

    def showLoadOriDialog(self):

        fname, _ = QtGui.QFileDialog.getOpenFileName(self, 'Open file',
                                                     '/home',
                                                     "Text files (*.txt)")
        if fname != None and fname != '':
            self.oriPointsPath = fname

    def showLoadRegionDialog(self):

        fname, _ = QtGui.QFileDialog.getOpenFileName(self, 'Open file',
                                                     '/home',
                                                     "Text files (*.txt)")
        if fname != None and fname != '':
            self.regionsPath = fname

    def showLoadProtoDialog(self):

        fname, _ = QtGui.QFileDialog.getOpenFileName(self, 'Open file',
                                                     '/home',
                                                     "Text files (*.txt)")
        if fname != None and fname != '':
            self.protoPointsPath = fname

    def showOriDialog(self):

        fname, _ = QtGui.QFileDialog.getOpenFileName(
            self, 'Open file', '/home', "Image Files (*.png *.jpg *.bmp)")
        if fname != None and fname != '':
            self.oriPath = fname
            print(self.oriPath)
            self.oriLabel.setPixmap(QPixmap(self.oriPath))

    #Connected with eSld change the e value in LAT method
    def changeEValue(self, x):
        self.e = 4.0 * x / 10**5
        self.eLabel.setText('E Value:' + str('%.2f' % self.e))

    #Connected with aSld change the alpha value in MLS and Morphing method(but the alpha range is not the same)
    def changeAlphaValue(self, x):
        if self.transform == 'Moving Least Squares':
            self.alpha = 2.0 * x / 10**5
        elif self.transform == 'Morphing':
            self.alpha = 1.0 * x / 10**5
        self.aLabel.setText('Alpha Value:' + str('%.2f' % self.alpha))

    #Connected to the method combobox
    def affineChoiceChange(self, item):

        if self.transform in ['Moving Least Squares', 'Morphing'] and item in [
                'Moving Least Squares', 'Morphing'
        ] and item != self.transform:
            self.alpha = 0.0
            self.aSld.setValue(self.alpha)
        self.transform = item

    #Connected to the distance combobox
    def distanceChoiceChange(self, item):
        self.oriImg, self.protoImg, self.protoPoints, self.affine_funs = preprocess(
            oriPath, protoPath, oriPointsPath, protoPointsPath, item)
Example #21
0
class View(QWidget):
    """Base `View` class. Defines behavior common in all views"""
    # Selecting a good font family for each platform
    osname = platform.system()
    if osname == 'Windows':
        fontFamily = 'Segoe UI'
    elif osname == 'Linux':
        fontFamily = ''
    else:
        fontFamily = ''

    def __init__(self, parent=None):
        """
        Init method. Initializes parent classes
        
        :param parent: Reference to a `QWidget` object to be used as parent 
        """

        super(View, self).__init__(parent)

    @staticmethod
    def labelsFont():
        """Returns the `QFont` that `QLabels` should use"""

        return View.font(True)

    @staticmethod
    def editsFont():
        """Returns the `QFont` that `QLineEdits` should use"""

        return View.font(False)

    @staticmethod
    def font(bold):
        """
        Returns a `QFont` object to be used in `View` derived classes.
        
        :param bold: Indicates whether or not the font will be bold
        """

        font = QFont(View.fontFamily, 9, 50, False)
        font.setBold(bold)

        return font

    def setLogo(self):
        """Sets the company logo in the same place in all views"""

        logoPixmap = QPixmap(':/resources/logo.png')
        self.iconLabel = QLabel(self)
        self.iconLabel.setPixmap(logoPixmap)
        self.iconLabel.setGeometry(20, 20, logoPixmap.width(),
                                   logoPixmap.height())

        self.linkLabel = QLabel(self)
        self.linkLabel.setText(
            """<font size="1"><a href="http://www.iqstorage.com/fromiqbox.php">
                Developed at IQ Storage FTP Hosing Services</a></font>""")
        self.linkLabel.setOpenExternalLinks(True)
        # Defines a visual line separator to be placed under the `logoPixmap` `QLabel`
        self.line = QFrame()
        self.line.setFrameShape(QFrame.HLine)
        self.line.setFrameShadow(QFrame.Sunken)
Example #22
0
# Import modules
import sys
#import paramiko

from PySide.QtCore import Qt
from PySide.QtGui import QApplication, QLabel
# Main 
if __name__ == '__main__':
	myApp = QApplication(sys.argv)
# Create all labels and set their properties
	appLabel = QLabel()
	appLabel.setText("Hello, World!!!\n lukasz_uszko 2014")
	appLabel.setAlignment(Qt.AlignCenter)
	appLabel.setWindowTitle("Uszko_Test_App")
	appLabel.setGeometry(300, 300, 300, 300)
	appLabel.show()
	 
 
	# hostname = "172:16:1:102"
	# password = "******"
	# command = "ls"
 
	# username = "******"
	# port = 22
 
	# try:
		# client = paramiko.SSHClient()
		# client.load_system_host_keys()
		# client.set_missing_host_key_policy(paramiko.WarningPolicy)
    
		# client.connect(hostname, port=port, username=username, password=password)
#coding:utf-8
# åƼ兄åæ…é”»ęؔ块
import sys
from PySide.QtCore import Qt
from PySide.QtGui import QApplication, QLabel, QPushButton


def cmd_print_info():
    print "cmd_print"


# äø»å‡½ę•°
if __name__ == '__main__':
    myApp = QApplication(sys.argv)  # 创å»ŗLabelå¹¶č®¾ē½®å®ƒēš„å±žę€§
    button = QPushButton(u"ęŒ‰é’®ęµ‹čƕ")
    button.clicked.connect(cmd_print_info)
    appLabel = QLabel()
    appLabel.setText(u"<font color=red size=40>čæ™ę˜Æꈑēš„ē¬¬äø€äøŖPySideē؋åŗ</font>")
    appLabel.setAlignment(Qt.AlignCenter)
    appLabel.setWindowTitle(u"PySide굋čƕē؋åŗ")
    appLabel.setGeometry(300, 300, 600, 300)
    appLabel.show()  # ę˜¾ē¤ŗčæ™äøŖLabel
    button.show()  # čæč”Œmain application
    myApp.exec_()
    sys.exit()
Example #24
0
    import urllib2
    print 'import urllib2'
    import time
    print 'all imports done (time last import)'
    raise

    print 'Before anything apart from importing'

    app = QApplication(sys.argv)
    update_dialog = QWidget()
    update_dialog.resize(350, 100)
    update_dialog.setWindowTitle('Updater')
    update_dialog.show()

    update_dialog_lbl = QLabel(update_dialog)
    update_dialog_lbl.setGeometry(10, 40, 340, 25)
    update_dialog_lbl.setOpenExternalLinks(True)
    update_dialog_lbl.setText('Updating! (Screen will hang, it\'s normal.)')

    # sys.exit(app.exec_())

    running = True
    versionNew = 0
    success = False

    updater()
    # this code will stall the rest of the code until the thread says 'running = False'
    # This means that the code past this will run only after the thread said
    # it could do that.
    while running:
        time.sleep(1)
class LoadingWidget(QWidget):
  """A widget with a little animation for showing progress.
    Call setMessage to change the secondary message and emit
    the finished signal with an appropriate string to set as the
    primary message when done.
  """
  finished = Signal(str)
  animation_finished = Signal()
  
  def __init__(self, loadIcon="loading_bar", primaryMessage="Please, Wait", message='', parent=None):
    super(LoadingWidget, self).__init__(parent)
    self.finished.connect(self._updateUI)
    self.setStyleSheet("""
      QWidget {
        background-color: #ffffff
      }
    """)
    self._icon_load = loadIcon
    self._primary_message = primaryMessage
    self._label_message = QLabel(message)
    self._label_message.setWordWrap(True)
    self._label_message.setAlignment(Qt.AlignCenter)
    self._label_primary_message = QLabel(self._primary_message)
    self._label_primary_message.setStyleSheet("""
      QLabel {
        font-size: 20px;
        font-weight:bold;
        color: rgb(65,65,65);
      }
    """)
    self._label_primary_message.setAlignment(Qt.AlignCenter)
    self._label_movie = QLabel()
    self._label_movie.setAlignment(Qt.AlignCenter)
    self._movie = QMovie(self._icon_load)
    self._label_movie.setMovie(self._movie)
    self._movie.start()
    layout = QVBoxLayout()
    layout.addWidget(self._label_primary_message)
    layout.addSpacing(5)
    layout.addWidget(self._label_message)
    layout.addSpacing(5)
    layout.addWidget(self._label_movie)
    layout.addStretch()
    #self._setupAnimation() # this should be done after showing everything to get correct geometries
    self.setLayout(layout)
  
  def _setupAnimation(self):
    self._load_animation = QPropertyAnimation(self._label_movie, "geometry")
    # since the opacity is failing, make it run out of the area!
    anim_label_geom = self._label_movie.geometry()
    self._load_animation.setStartValue(anim_label_geom)
    target_anim_geom = QRect(anim_label_geom)
    target_anim_geom.moveTop(self.height())
    # make the animation target a rectangle that's directly under it but shifted downwards outside of parent
    self._load_animation.setEndValue(target_anim_geom)
    self._load_animation.setEasingCurve(QEasingCurve.InBack)
    self._load_animation.setDuration(1000)
    self._load_animation.finished.connect(self.animation_finished)
    self._load_animation.finished.connect(self._hideAnimLabel)
  
  def setMessage(self, message):
    self._label_message.setText(message)
    
  def _updateUI(self, message=''):
    if not message:
      message = "All Done!"
    self._label_primary_message.setText(message)
    self._label_message.setText('')
    self._movie.stop()
    self._setupAnimation()
    self.layout().removeWidget(self._label_movie)
    self._label_movie.setGeometry(self._load_animation.startValue())
    self._load_animation.start()
    
  def _hideAnimLabel(self):
    self._label_movie.hide()
    
Example #26
0
class ImageBase(QLabel):

    def __init__(self, *args, **kwargs):
        
        self.transInfo = ImageBaseTranslateInfo()
        
        super(ImageBase, self).__init__(*args, **kwargs)
        self.installEventFilter(self)
        
        self.image            = QImage()
        self.pixmap = QPixmap()
        self.label = QLabel(self)
        self.imagePath = ""
        self.aspect = 1
        self.imageClean = True
    
    
    def clearImage(self):
        
        self.label.clear()
        self.imageClean = True

    
    
    def loadImage(self, filePath ):
        
        self.imageClean = False
        if self.imagePath == filePath: return None
        self.imagePath = filePath
        
        self.aspect = 1
        if self.image.load(filePath): pass
        self.transInfo.setDefault()

        widgetSize = min( self.parentWidget().width(), self.parentWidget().height()  ) * 0.9
        imageWidth = self.image.width()
        
        self.transInfo.scale = widgetSize / float( imageWidth )
        self.resize()
        

    def resize(self):
        
        if self.imageClean: return None
        
        trValue = QTransform().scale( self.transInfo.scaleX(), self.transInfo.scaleY() )
        trValue *= QTransform().rotate( self.transInfo.rotValue )
        imageTransformed = self.image.transformed(trValue)
        
        imageWidth  = imageTransformed.width()
        imageHeight = imageTransformed.height()
        
        self.pixmap = QPixmap.fromImage( imageTransformed )
        self.label.setPixmap( self.pixmap )
        
        marginLeft = (self.width() - imageWidth)/2.0
        marginTop  = (self.height() - imageHeight)/2.0
        
        self.label.setGeometry( marginLeft + self.transInfo.x,marginTop + self.transInfo.y, imageWidth, imageHeight )
        self.label.paintEvent(QPaintEvent(QtCore.QRect( 0,0,self.width(), self.height() )))
        
        
    def flip(self, pressX ):
        
        offsetX = pressX - self.width()/2
        
        self.transInfo.rotValue *= -1
        self.transInfo.x = (self.transInfo.x - offsetX)*-1 + offsetX
        self.transInfo.scaleMultX *= -1
        
        self.resize()
        
    
    def show( self ):
        self.label.show()
    

    def eventFilter( self, Obj, event ):
        
        if event.type() == QtCore.QEvent.Resize:
            self.resize()
        elif event.type() == QtCore.QEvent.MouseButtonPress:
            pressX = event.x()-self.width()/2
            pressY = event.y()-self.height()/2
            self.transInfo.buttonPress(event.button(), pressX, pressY )
        elif event.type() == QtCore.QEvent.MouseButtonRelease:
            if self.transInfo.x == self.transInfo.bx and self.transInfo.y == self.transInfo.by:
                pass
            self.transInfo.buttonRelease()
            Window_global.saveInfo()
        elif event.type() == QtCore.QEvent.MouseMove:
            pressX = event.x()-self.width()/2
            pressY = event.y()-self.height()/2
            self.transInfo.drag( pressX, pressY )
            self.resize()
        elif event.type() == QtCore.QEvent.MouseButtonDblClick:
            self.flip( event.x() )
        elif event.type() == QtCore.QEvent.Wheel:
            pressX = event.x()-self.width()/2
            pressY = event.y()-self.height()/2
            self.transInfo.buttonPress( QtCore.Qt.RightButton , pressX, pressY)
            self.transInfo.drag( pressX + event.delta()/2, pressY )
            self.transInfo.buttonRelease()
            self.resize()
            Window_global.saveInfo()
        return True
Example #27
0
#! /usr/bin/env/python
# -*- coding:utf-8 -*-
__author__ = 'tim'

import sys
from PySide.QtCore import Qt
from PySide.QtGui import QApplication,QLabel

if __name__ == '__main__':
    app=QApplication(sys.argv)

    label=QLabel()
    label.setText("hello world")
    label.setAlignment(Qt.AlignCenter)
    label.setWindowTitle('My First Application')
    label.setGeometry(300,300,350,100)

    label.show()

    sys.exit(app.exec_())
Example #28
0
class optdlg(QDialog):
	def __init__(self, parent=None):
		super(optdlg, self).__init__(parent)
		self.setFixedSize(484, 399)
		appicom = QIcon(":/icons/njnlogo.png")
		self.setWindowIcon(appicom)
		self.setWindowTitle("Nigandu English to Tamil Dictionary | OPTIONS")

		self.buttonBox = QDialogButtonBox(self)
		self.buttonBox.setEnabled(True)
		self.buttonBox.setGeometry(QRect(350, 20, 121, 200))

		self.buttonBox.setOrientation(Qt.Vertical)
		self.buttonBox.setStandardButtons(QDialogButtonBox.Apply|QDialogButtonBox.Cancel|QDialogButtonBox.Ok)
		self.buttonBox.setCenterButtons(True)
		self.restorebtn = QPushButton(self)
		self.restorebtn.setGeometry(QRect(354, 360, 121, 23))
		self.restorebtn.setText("&RestoreDefults")

		self.fontbox = QGroupBox(self)
		self.fontbox.setGeometry(QRect(10, 10, 331, 141))
		self.spinBox = QSpinBox(self.fontbox)
		self.spinBox.setGeometry(QRect(100, 20, 81, 21))
		self.spinBox.setMinimum(10)
		self.spinBox.setMaximum(24)
		self.label = QLabel(self.fontbox)
		self.label.setGeometry(QRect(20, 20, 71, 21))
		self.label.setText("Font Size:")
		self.fontbox.setTitle("Font")
		self.samplefontbox = QGroupBox(self)
		self.samplefontbox.setGeometry(QRect(20, 50, 291, 91))
		self.samplefontbox.setTitle("Sample Text")
		self.sampletxt = QLabel(self.samplefontbox)
		self.sampletxt.setGeometry(QRect(20, 20, 251, 61))
		self.sampletxt.setText("AaBbCcDdEeFfGgHhIiJjKkLlYyZz")

		self.clipbox = QGroupBox(self)
		self.clipbox.setGeometry(QRect(10, 160, 331, 61))
		self.clipbox.setTitle("ClipBoard Options")
		self.checkclip = QCheckBox(self.clipbox)
		self.checkclip.setGeometry(QRect(20, 20, 301, 31))
		self.checkclip.setText("Allow copy from clipboard on start-up")


		self.histbox = QGroupBox(self)
		self.histbox.setGeometry(QRect(10, 230, 331, 91))
		self.histbox.setTitle("History")
		self.checkshowhistdock = QCheckBox(self.histbox)
		self.checkshowhistdock.setGeometry(QRect(20, 60, 301, 17))

		self.checkshowhistdock.setText("Show History Dock on the right side")
		self.checkdelhist = QCheckBox(self.histbox)
		self.checkdelhist.setGeometry(QRect(20, 30, 301, 17))
		self.checkdelhist.setText("Clear all the past history records")

		self.bkmbox = QGroupBox(self)
		self.bkmbox.setGeometry(QRect(10, 330, 331, 61))
		self.bkmbox.setTitle("Book Marks")
		self.checkshowbkmdock = QCheckBox(self.bkmbox)
		self.checkshowbkmdock.setGeometry(QRect(20, 30, 301, 17))
		self.checkshowbkmdock.setText("Show Book Marks Dock on the right side.")

		self.spinBox.valueChanged[int].connect(self.setsampletxt)
		self.restorebtn.clicked.connect(self.setdeafults)
		self.buttonBox.rejected.connect(self.close)


	def setdeafults(self):
		self.spinBox.setValue(13)
		self.checkshowhistdock.setChecked(True)
		self.checkshowbkmdock.setChecked(True)
		self.checkclip.setChecked(True)
		self.checkdelhist.setChecked(False)

	def setsampletxt(self, i):
		font = QFont()
		font.setPixelSize(i)
		self.sampletxt.setFont(font)
        myWindow.setIcon()

        myWindow.setButton()
        myWindow.setIconModes()
        myWindow.center()
        myWindow.setAboutButton()
        
        myWindow.show()
        myApp.exec_()
        sys.exit(0)
    except NameError:
        print("Name Error:", sys.exc_info()[1])
    except SystemExit:
        print("Closing Window...")
    except Exception:
        print(sys.exc_info()[1])
# Main Function
if __name__ == '__main2__':
    # Create the main application
    myApp = QApplication(sys.argv)
    # Create a Label and set its properties
    appLabel = QLabel()
    appLabel.setText("Hello, World!!!\n Look at my first app using PySide")
    appLabel.setAlignment(Qt.AlignCenter)
    appLabel.setWindowTitle("My First Application")
    appLabel.setGeometry(300, 300, 250, 175)
    # Show the Label
    appLabel.show()
    # Execute the Application and Exit
    myApp.exec_()
    sys.exit()
Example #30
0
win = app.desktop().screenGeometry()

signal.signal(signal.SIGINT, handler)

#---- kong ---- for RPi
f = os.popen('hostname -I')
r = f.read()
ip = r.split(' ')[0]
#----

t = QTimer()
t.setSingleShot(True)
t.timeout.connect(handler)
t.start(10000)

url = QLabel()
url.setWindowFlags(Qt.FramelessWindowHint)
url.setGeometry(win)
url.setAttribute(Qt.WA_DeleteOnClose, False)
url.setFocusPolicy(Qt.NoFocus)
url.setContextMenuPolicy(Qt.NoContextMenu)
url.setStyleSheet('background-color: black;')
url.setText('<font size=10 color=white>http://%s:8080</font>' % ip)
url.setAlignment(Qt.AlignCenter)
url.show()

sys.exit(app.exec_())

#
#
#
class AddPresetDialog(QDialog):
    def __init__(self, parent=None):
        super(AddPresetDialog, self).__init__(parent)

        self.setWindowTitle(self.tr("Add IMAP Server Preset"))
        self.resize(388, 125)
        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setGeometry(QRect(184, 80, 181, 32))
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setCenterButtons(False)
        self.save_btn = QPushButton("&Save")
        self.save_btn.setDefault(True)
        self.save_btn.setEnabled(False)
        self.cancel_btn = QPushButton(self.tr("&Cancel"))
        self.cancel_btn.setCheckable(True)
        self.cancel_btn.setAutoDefault(False)

        self.buttonBox.addButton(self.save_btn, QDialogButtonBox.AcceptRole)
        self.buttonBox.addButton(self.cancel_btn, QDialogButtonBox.RejectRole)

        self.preset_name_le = QLineEdit(self)
        self.preset_name_le.setGeometry(QRect(134, 12, 231, 20))
        self.lb_name = QLabel(self)
        self.lb_name.setGeometry(QRect(14, 16, 58, 14))
        self.lb_name.setText(self.tr("Name"))
        self.server_address_le = QLineEdit(self)
        self.server_address_le.setGeometry(QRect(134, 45, 231, 20))
        self.lb_server = QLabel(self)
        self.lb_server.setGeometry(QRect(14, 48, 81, 16))
        self.lb_server.setText(self.tr("IMAP Server"))
        self.lb_info = QLabel(self)
        self.lb_info.setGeometry(QRect(14, 90, 161, 16))
        self.lb_info.setText(self.tr("(SSL is always on.)"))

        self.buttonBox.accepted.connect(self.act_save_preset)
        self.buttonBox.rejected.connect(self.reject)

        self.init_settings()

        self.settings.beginGroup("Server Presets")
        self.presetNameList = []
        for preset in self.settings.allKeys():
            self.presetNameList.append(preset)
        self.settings.endGroup()

        self.preset_name_le.textChanged.connect(self.check_preset_name_availability)
        self.server_address_le.textChanged.connect(self.check_server_address)

    # ---------------------------------------------------------------------
    def init_settings(self):
        QCoreApplication.setOrganizationName("erdinc.me")
        QCoreApplication.setOrganizationDomain("erdinc.me")
        QCoreApplication.setApplicationName("IMAPLinkParser")
        self.settings = QSettings()
        # self.settings.clear()

    # ---------------------------------------------------------------------
    @Slot()
    def act_save_preset(self):
        try:
            self.settings.beginGroup("Server Presets")
            self.settings.setValue(self.preset_name_le.text(), self.server_address_le.text())
            self.settings.endGroup()
        except:
            self.reject()
        self.accept()

    # ---------------------------------------------------------------------
    @Slot(unicode)
    def check_preset_name_availability(self, text):
        if text in self.presetNameList:
            self.save_btn.setEnabled(False)
            self.lb_info.setText('<p style="color:red;">Preset name exists!')
        else:
            if self.server_address_le.text() and self.preset_name_le.text():
                self.save_btn.setEnabled(True)
                self.lb_info.setText(self.tr("(SSL is always on.)"))
            else:
                self.save_btn.setEnabled(False)
                self.lb_info.setText(self.tr("(SSL is always on.)"))

    # ---------------------------------------------------------------------
    @Slot(unicode)
    def check_server_address(self):
        if self.server_address_le.text():
            preset = self.preset_name_le.text()
            if preset and preset not in self.presetNameList:
                self.save_btn.setEnabled(True)
        else:
            self.save_btn.setEnabled(False)
Example #32
0
    def __init__(self, parent):
        super(RotationControl, self).__init__(parent)
        self.parent = parent
        # get style metrics
        style = self.parent.app.style()
        fm = self.parent.app.fontMetrics()
        self.leftMargin = style.pixelMetric(QStyle.PM_LayoutLeftMargin)
        self.topMargin = style.pixelMetric(QStyle.PM_LayoutTopMargin)
        standHeight = style.pixelMetric(QStyle.PM_ButtonMargin) + fm.height() + 2
        doubleStandHeight = standHeight * 2
        hsepara = style.pixelMetric(QStyle.PM_LayoutHorizontalSpacing)
        vsepara = style.pixelMetric(QStyle.PM_LayoutVerticalSpacing)
        # calculate grids
        col0Left = self.leftMargin
        col1Left = self.leftMargin + doubleStandHeight + vsepara
        col2Left = self.leftMargin + doubleStandHeight + standHeight + 2*vsepara
        col3Left = self.leftMargin + 2*doubleStandHeight + standHeight + 4*vsepara
        row0Top = self.topMargin
        row1Top = self.topMargin + standHeight + hsepara
        row2Top = self.topMargin + 3*standHeight + 2*hsepara
        row3Top = self.topMargin + 4*standHeight + 3*hsepara
    
        btnUp = QPushButton('Up', self)
        btnUp.setGeometry(col1Left, row1Top, standHeight, doubleStandHeight)
        btnUp.clicked.connect(self.btnUp_OnClick)

        btnLeft = QPushButton('Left', self)
        btnLeft.setGeometry(col0Left, row2Top, doubleStandHeight, standHeight)
        btnLeft.clicked.connect(self.btnLeft_OnClick)

        self.txtQuant = QLineEdit(self)
        self.txtQuant.setObjectName('txtQuant')
        self.txtQuant.setGeometry(col1Left, row2Top, standHeight, standHeight)
        self.txtQuant.setAlignment(Qt.AlignVCenter | Qt.AlignCenter)
        self.txtQuant.setText('5')

        btnRight = QPushButton('Right', self)
        btnRight.setGeometry(col2Left, row2Top, doubleStandHeight, standHeight)
        btnRight.clicked.connect(self.btnRight_OnClick)

        btnDown = QPushButton('Dn', self)
        btnDown.setObjectName('btnDown')
        btnDown.setGeometry(col1Left, row3Top, standHeight, doubleStandHeight)
        btnDown.clicked.connect(self.btnDown_OnClick)

        lb3 = QLabel('Elevation:', self)
        lb3.setGeometry(col3Left, row2Top, lb3.sizeHint().width(), standHeight)

        wi = fm.width('Horizontal:') + 2
        lb4 = QLabel('Horizontal:', self)
        lb4.setGeometry(col3Left, row3Top, wi, standHeight)
        col4Left = self.leftMargin + 2*doubleStandHeight + standHeight + 5*vsepara + wi
    
        txtElev = QLineEdit(self)
        txtElev.setObjectName('txtElev')
        txtElev.setGeometry(col4Left, row2Top, doubleStandHeight, standHeight)
        txtElev.setAlignment(Qt.AlignVCenter | Qt.AlignCenter)
        txtElev.setText(str(self.parent.renderArea.alef))

        txtHoriz = QLineEdit(self)
        txtHoriz.setObjectName('txtHoriz')
        txtHoriz.setGeometry(col4Left, row3Top, doubleStandHeight, standHeight)
        txtHoriz.setAlignment(Qt.AlignVCenter | Qt.AlignCenter)
        txtHoriz.setText(str(self.parent.renderArea.bet))

        lb2 = QLabel('Angles in degrees', self)
        lb2.setGeometry(col3Left, row2Top - standHeight - hsepara, wi + hsepara + doubleStandHeight, standHeight)
        lb2.setAlignment(Qt.AlignVCenter | Qt.AlignCenter) #Qt.AlignVCenter

        self.totalWi = col4Left + doubleStandHeight - col0Left
        self.totalHi = row3Top + doubleStandHeight - row0Top
        lb1 = QLabel('Camera position control panel', self)
        lb1.setGeometry(col0Left, row0Top, self.totalWi, standHeight)
        lb1.setAlignment(Qt.AlignVCenter | Qt.AlignCenter)
        self.width_ = col4Left + doubleStandHeight + vsepara
        #lb1.setFrameStyle(QFrame.Box)
        self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)