コード例 #1
0
 def __init__(self, autoaccept=False, parent=None):
     """
     :param autoaccept: if True, the value of the ComboBox is immediately
     accepted after selecting it.
     """
     super(ComboBoxInputDialog, self).__init__(parent)
     self._autoaccept = autoaccept
     layout = QVBoxLayout()
     label = QtGui.QLabel()
     label.setObjectName( 'label' )
     combobox = QtGui.QComboBox()
     combobox.setObjectName( 'combobox' )
     combobox.activated.connect( self._combobox_activated )
     ok_button = QPushButton('OK')
     ok_button.setObjectName( 'ok' )
     cancel_button = QPushButton('Cancel')
     cancel_button.setObjectName( 'cancel' )
     ok_button.pressed.connect(self.accept)
     cancel_button.pressed.connect(self.reject)
     button_layout = QBoxLayout(QBoxLayout.RightToLeft)
     button_layout.addWidget(cancel_button)
     button_layout.addWidget(ok_button)
     layout.addWidget( label )
     layout.addWidget( combobox )
     layout.addLayout( button_layout )
     self.setLayout( layout )
コード例 #2
0
ファイル: qpagewidget.py プロジェクト: pars-linux/uludag
    def __init__(self, parent=None, direction="ltr", rtf=False):
        """ Creates a new QPageWidget on given parent object. 

        parent: QWidget parent
        direction: "ltr" -> Left To Right
                   "ttb" -> Top To Bottom
        rtf: Return to first, if its True it flips to the first page 
             when next page requested at the last page
        """
        # First initialize, QPageWidget is based on QScrollArea
        QScrollArea.__init__(self, parent)

        # Properties for QScrollArea
        self.setFrameShape(QFrame.NoFrame)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setWidgetResizable(True)

        # Main widget, which stores all Pages in it
        self.widget = QWidget(self)

        # Layout based on QBoxLayout which supports Vertical or Horizontal layout
        if direction == "ltr":
            self.layout = QBoxLayout(QBoxLayout.LeftToRight, self.widget)
            self.__scrollBar = self.horizontalScrollBar()
            self.__base_value = self.width
        else:
            self.layout = QBoxLayout(QBoxLayout.TopToBottom, self.widget)
            self.__scrollBar = self.verticalScrollBar()
            self.__base_value = self.height
        self.layout.setSpacing(0)
        self.layout.setMargin(0)

        # Return to first
        self.__return_to_first = rtf

        # TMP_PAGE, its using as last page in stack
        # A workaround for a QScrollArea bug
        self.__tmp_page = Page(QWidget(self.widget))
        self.__pages = [self.__tmp_page]
        self.__current = 0
        self.__last = 0

        # Set main widget
        self.setWidget(self.widget)

        # Animation TimeLine
        self.__timeline = QTimeLine()
        self.__timeline.setUpdateInterval(2)

        # Updates scrollbar position when frame changed
        self.__timeline.frameChanged.connect(
            lambda x: self.__scrollBar.setValue(x))

        # End of the animation
        self.__timeline.finished.connect(self._animateFinished)

        # Initialize animation
        self.setAnimation()
        self.setDuration()
コード例 #3
0
ファイル: qpagewidget.py プロジェクト: Pardus-Linux/pds
    def __init__(self, parent = None, direction = "ltr", rtf = False):
        """ Creates a new QPageWidget on given parent object. 

        parent: QWidget parent
        direction: "ltr" -> Left To Right
                   "ttb" -> Top To Bottom
        rtf: Return to first, if its True it flips to the first page 
             when next page requested at the last page
        """
        # First initialize, QPageWidget is based on QScrollArea
        QScrollArea.__init__(self, parent)

        # Properties for QScrollArea
        self.setFrameShape(QFrame.NoFrame)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setWidgetResizable(True)

        # Main widget, which stores all Pages in it
        self.widget = QWidget(self)

        # Layout based on QBoxLayout which supports Vertical or Horizontal layout
        if direction == "ltr":
            self.layout = QBoxLayout(QBoxLayout.LeftToRight, self.widget)
            self.__scrollBar = self.horizontalScrollBar()
            self.__base_value = self.width
        else:
            self.layout = QBoxLayout(QBoxLayout.TopToBottom, self.widget)
            self.__scrollBar = self.verticalScrollBar()
            self.__base_value = self.height
        self.layout.setSpacing(0)
        self.layout.setMargin(0)

        # Return to first
        self.__return_to_first = rtf

        # TMP_PAGE, its using as last page in stack
        # A workaround for a QScrollArea bug
        self.__tmp_page = Page(QWidget(self.widget))
        self.__pages = [self.__tmp_page]
        self.__current = 0
        self.__last = 0

        # Set main widget
        self.setWidget(self.widget)

        # Animation TimeLine
        self.__timeline = QTimeLine()
        self.__timeline.setUpdateInterval(2)

        # Updates scrollbar position when frame changed
        self.__timeline.frameChanged.connect(lambda x: self.__scrollBar.setValue(x))

        # End of the animation
        self.__timeline.finished.connect(self._animateFinished)

        # Initialize animation
        self.setAnimation()
        self.setDuration()
コード例 #4
0
 def __init__(self, labelText=QString(), topLeftTuple=LEFT, parent=None):
     super(LabelledTextEdit, self).__init__(parent)
     self.label = QLabel(labelText)
     self.textEdit = QTextEdit()
     self.label.setBuddy(self.textEdit)
     layout = QBoxLayout(QBoxLayout.LeftToRight
             if topLeftTuple == LEFT else QBoxLayout.TopToBottom)
     layout.addWidget(self.label)
     layout.addWidget(self.textEdit)
     self.setLayout(layout)
コード例 #5
0
 def init_ui(self):
     """
     UI setup.
     """
     layout = QBoxLayout(0, self)
     self.setLayout(layout)
     layout.addWidget(self.view)
     self.view.move(0, 0)
     #self.view.resize(self.parent().width(), self.parent().height())
     self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
コード例 #6
0
ファイル: gui.py プロジェクト: philipstahl/emotutor
    def init_parameters(self):
        """ Creates the layout of the settings screen
        """
        net_layout = QGridLayout()

        net_layout.addWidget(QLabel("MARC:"), 0, 1)
        net_layout.addWidget(QLabel("WASABI:"), 0, 2)

        label_network = QLabel("Network:")
        label_network.setStyleSheet("QLabel {font-weight:bold}")

        net_layout.addWidget(label_network, 1, 0)

        net_layout.addWidget(QLabel("IP:"), 2, 0)
        net_layout.addWidget(self.marc_settings["ip"], 2, 1)
        net_layout.addWidget(self.wasabi_settings["ip"], 2, 2)

        net_layout.addWidget(QLabel("Input Port:"), 3, 0)
        net_layout.addWidget(self.marc_settings["port_in"], 3, 1)
        net_layout.addWidget(self.wasabi_settings["port_in"], 3, 2)

        net_layout.addWidget(QLabel("Output Port:"), 4, 0)
        net_layout.addWidget(self.marc_settings["port_out"], 4, 1)
        net_layout.addWidget(self.wasabi_settings["port_out"], 4, 2)

        button_test_wasabi = QPushButton("&Test")
        button_test_wasabi.clicked.connect(self.test_wasabi)

        net_layout.addWidget(button_test_wasabi, 4, 3)

        net_values = QWidget()
        net_values.setLayout(net_layout)

        # Open Mary:
        label_mary = QLabel("Open Mary:")
        label_mary.setStyleSheet("QLabel {font-weight:bold}")

        layout_mary = QGridLayout()
        layout_mary.addWidget(label_mary, 0, 0)
        layout_mary.addWidget(QLabel("Request:"), 1, 0)
        layout_mary.addWidget(QLabel("Voice:"), 2, 0)
        layout_mary.addWidget(QLabel("Path:"), 3, 0)
        layout_mary.addWidget(self.mary_settings["ip"], 1, 1)
        layout_mary.addWidget(self.mary_settings["voice"], 2, 1)
        layout_mary.addWidget(self.mary_settings["path"], 3, 1)
        widget_mary = QWidget()
        widget_mary.setLayout(layout_mary)

        main_layout = QBoxLayout(2)
        main_layout.addWidget(net_values)
        main_layout.addWidget(widget_mary)
        main_widget = QWidget()
        main_widget.setLayout(main_layout)
        return main_widget
コード例 #7
0
ファイル: labelledwidgets.py プロジェクト: dpeinado/restec
 def __init__(self, labelText=QString(), position=LEFT,
              parent=None):
     super(LabelledLineEdit, self).__init__(parent)
     self.label = QLabel(labelText)
     self.lineEdit = QLineEdit()
     self.label.setBuddy(self.lineEdit)
     layout = QBoxLayout(QBoxLayout.LeftToRight
             if position == LEFT else QBoxLayout.TopToBottom)
     layout.addWidget(self.label)
     layout.addWidget(self.lineEdit)
     self.setLayout(layout)
コード例 #8
0
 def _create_radiobutton(self, key, value):
     atomic_widget = QWidget()
     layout = QBoxLayout(self.horizontal)
     for i, rbkey in enumerate(self.radiobuttons[key][0]):
         b1 = QRadioButton("Button1")
         if i == self.radiobuttons[key][1]:
             b1.setChecked(True)
         # b1.toggled.connect(lambda:self.btnstate(self.b1))
         layout.addWidget(b1)
     atomic_widget.setLayout(layout)
     return atomic_widget
コード例 #9
0
ファイル: dbus_denemesi.py プロジェクト: pars-linux/uludag
    def __init__ (self):
        QWidget.__init__ (self)
        

        self.sessionBus = dbus.SessionBus()
        self.systemBus = dbus.SystemBus()
        
        self.powerdevil = self.sessionBus.get_object('org.kde.screensaver', '/App') 
        self.powerdevil2 = self.sessionBus.get_object('org.kde.screensaver', '/ScreenSaver') 
        #self.powerdevil3 = self.sessionBus.get_object('org.kde.kopete', '/Kopete') 
        #self.powerdevil4 = self.sessionBus.get_object('org.kde.kopete', '/Kopete') 
        #self.powerdevil5 = self.sessionBus.get_object('org.kde.kopete', '/Kopete') 
        self.powerdevil6 = self.sessionBus.get_object('org.kde.plasma-desktop', '/App') 
        #self.powerdevil7 = self.sessionBus.get_object('org.kde.yakuake', '/yakuake/MainWindow_1') 
        #self.powerdevil8 = self.sessionBus.get_object('org.kde.amarok', '/Player') 
        #self.sistemeGonder=self.systemBus.get_object('tr.org.pardus.comar','/package/iptables')
        self.sistemeGonder=self.systemBus.get_object('tr.org.pardus.comar','/package/openssh')
        
        
        self.layout = QBoxLayout(QBoxLayout.TopToBottom, self)
        self.setLayout(self.layout)
        
        label = QLabel ("bir program", self)
        self.layout.addWidget(label)
 
	button0 = QPushButton("comarrr!", self)
        self.layout.addWidget(button0)
        button = QPushButton("yazdir!", self)
        self.layout.addWidget(button)
        button2 = QPushButton("ekrani kilitle!", self)
        self.layout.addWidget(button2)
        button3 = QPushButton("kopete baglantisini kes!", self)
        self.layout.addWidget(button3)
        button4 = QPushButton("canerle sohbet baslat!", self)
        self.layout.addWidget(button4)
        button6 = QPushButton("dashboardı goster!", self)
        self.layout.addWidget(button6)
        button7 = QPushButton("yakuake yi toogle et!", self)
        self.layout.addWidget(button7)
        button8 = QPushButton("amarok baslat/duraklat!", self)
        self.layout.addWidget(button8)
 
	QObject.connect(button0, SIGNAL("clicked()"), self.screenOff0)
        QObject.connect(button, SIGNAL("clicked()"), self.screenOff)
        QObject.connect(button2, SIGNAL("clicked()"), self.screenOff2)
        QObject.connect(button3, SIGNAL("clicked()"), self.screenOff3)
        QObject.connect(button4, SIGNAL("clicked()"), self.screenOff4)
        QObject.connect(button6, SIGNAL("clicked()"), self.screenOff6)
        QObject.connect(button7, SIGNAL("clicked()"), self.screenOff7)
        QObject.connect(button8, SIGNAL("clicked()"), self.screenOff8)
        
        self.resize (640, 480)
コード例 #10
0
 def __init__(self, actions=None, parent=None,
              direction=QBoxLayout.LeftToRight):
     QWidget.__init__(self, parent)
     self.actions = []
     self.buttons = []
     layout = QBoxLayout(direction)
     layout.setContentsMargins(0, 0, 0, 0)
     self.setContentsMargins(0, 0, 0, 0)
     self.setLayout(layout)
     if actions is not None:
         for action in actions:
             self.addAction(action)
     self.setLayout(layout)
コード例 #11
0
    def __init__(self, parent=None):
        super(XDockToolbar, self).__init__(parent)

        # defines the position for this widget
        self._currentAction = -1
        self._selectedAction = None
        self._padding = 8
        self._position = XDockToolbar.Position.South
        self._minimumPixmapSize = QSize(16, 16)
        self._maximumPixmapSize = QSize(48, 48)
        self._hoverTimer = QTimer()
        self._hoverTimer.setSingleShot(True)
        self._hoverTimer.setInterval(1000)
        self._actionHeld = False
        self._easingCurve = QEasingCurve(QEasingCurve.InOutQuad)
        self._duration = 200
        self._animating = False

        # install an event filter to update the location for this toolbar
        layout = QBoxLayout(QBoxLayout.LeftToRight)
        layout.setContentsMargins(2, 2, 2, 2)
        layout.setSpacing(0)
        layout.addStretch(1)
        layout.addStretch(1)

        self.setLayout(layout)
        self.setContentsMargins(2, 2, 2, 2)
        self.setMouseTracking(True)
        parent.window().installEventFilter(self)
        parent.window().statusBar().installEventFilter(self)

        self._hoverTimer.timeout.connect(self.emitActionHovered)
コード例 #12
0
 def __init__( self, parent = None ):
     super(XActionGroupWidget, self).__init__( parent )
     
     # define custom properties
     self._actionGroup   = None
     self._padding       = 5
     self._cornerRadius  = 10
     
     # set default properties
     layout = QBoxLayout(QBoxLayout.LeftToRight)
     layout.setContentsMargins(0, 0, 0, 0)
     layout.setSpacing(0)
     self.setSizePolicy( QSizePolicy.Preferred, QSizePolicy.Preferred )
     self.setLayout(layout)
コード例 #13
0
ファイル: gui.py プロジェクト: philipstahl/emotutor
    def __init__(self, parent=None):
        super(Welcome, self).__init__(parent)

        button_settings = QPushButton("&Edit settings")
        button_emotions = QPushButton("&Edit emotions")
        button_mapping = QPushButton("&Edit mapping")
        button_start = QPushButton("&Start training")

        button_start_user = QPushButton("&Start with applied settings.")
        button_start_neutral = QPushButton("&Start with neutral agent.")
        button_start_rulebased = QPushButton("&Start with rulebased agent.")
        button_start_wasabi = QPushButton("&Start with wasabi based agent.")

        # Define button funcionalty:
        button_settings.clicked.connect(self.options)
        button_emotions.clicked.connect(self.emotions)
        button_mapping.clicked.connect(self.mapping)

        button_start_user.clicked.connect(self.start_user)
        button_start_neutral.clicked.connect(self.start_neutral)
        button_start_rulebased.clicked.connect(self.start_rulebased)
        button_start_wasabi.clicked.connect(self.start_wasabi)

        button_layout = QBoxLayout(2)
        button_layout.addWidget(button_settings)
        button_layout.addWidget(button_emotions)
        button_layout.addWidget(button_mapping)
        buttons = QWidget()
        buttons.setLayout(button_layout)

        left_top = QWidget()
        left_bottom = QWidget()
        right_top = QWidget()
        right_bottom = QWidget()

        layout = QGridLayout()
        layout.addWidget(left_top, 0, 0)
        layout.addWidget(buttons, 0, 1)
        layout.addWidget(right_top, 0, 2)

        layout.addWidget(QLabel("Paired Associate Task:"), 1, 1)
        layout.addWidget(button_start_user, 2, 1)
        layout.addWidget(button_start_neutral, 3, 1)
        layout.addWidget(button_start_rulebased, 4, 1)
        layout.addWidget(button_start_wasabi, 5, 1)

        self.setLayout(layout)
        self.resize(600, 100)
コード例 #14
0
ファイル: docktitlebar.py プロジェクト: mprska/ricodebug
    def __init__(self, parent):
        QToolBar.__init__(self, parent)
        assert parent
        self.dock = parent

        # a fake spacer widget
        w = QWidget(self)
        l = QHBoxLayout(w)
        l.setMargin(0)
        l.setSpacing(0)
        l.addStretch()

        frame = QFrame()
        layout = QBoxLayout(QBoxLayout.LeftToRight, frame)
        layout.setContentsMargins(4, 4, 0, 0)
        layout.setSpacing(2)
        self.aDockFrame = self.addWidget(frame)

        self.__icon = QLabel()

        layout.addWidget(self.__icon)
        layout.addWidget(QLabel(self.dock.windowTitle()))

        self.dock.windowIconChanged.connect(self.__setWindowIcon)

        # fake spacer item
        spacer = QWidgetAction(self)
        spacer.setDefaultWidget(w)

        self.setMovable(False)
        self.setFloatable(False)
        self.setIconSize(QSize(12, 12))

        self.aFloat = QAction(self)
        self.aClose = QAction(self)

        QToolBar.addAction(self, spacer)
        self.separator = QToolBar.addSeparator(self)
        QToolBar.addAction(self, self.aFloat)
        QToolBar.addAction(self, self.aClose)

        self.updateStandardIcons()

        self.dockWidgetFeaturesChanged(self.dock.features())

        self.dock.featuresChanged.connect(self.dockWidgetFeaturesChanged)
        self.aFloat.triggered.connect(self._floatTriggered)
        self.aClose.triggered.connect(self.dock.close)
コード例 #15
0
ファイル: pyqtlearn.py プロジェクト: edeglau/storage
 def initUI(self):
     self.setWindowTitle("Expressions")
     self.layout = QVBoxLayout()
     self.btnlayout = QBoxLayout(2)
     self.playlist_names = QComboBox()
     self.layout.addLayout(self.btnlayout)
     self.label = QTextEdit()
     self.label.setText("nucleus1_wind_CTRL.windSpeed = abs( noise( frame * .05) * 8);\
         \n\n#connect:\
         \nlocator1_WIND.localWind =  abs( noise(sin(frame* .001)*8)*2)\
         \n\n#connect:\
         \nvortexField1.magnitude=turbulenceField1.magnitude;\
         \n\n#sine:\
         \npSphere1.translateY = sin(time);\
         \n\n#bounce:\
         \n$sine = sin(frame * .001);\
         \npSphere1.translateY =  abs( noise($sine) *4);\
         \n\n#bounce random:\
         \npSphere1.translateY =  abs( noise(sin(frame* .01) *2));\
         \n\n#offset:\
         \nint $currentTime=`currentTime -q`;\
         \nint $offset=5;\
         \n$offsetTime=$currentTime-$offset;\
         \n$getPos=`getAttr -t $offsetTime pSphere1.rotateY`;\
         \npSphere1.rotateY=$getPos;\
         \nint $offset=7;\
         \n$offsetTime=$currentTime-$offset;\
         \n$getPos=`getAttr -t $offsetTime pSphere1.rotateY`;\
         \npSphere2.rotateY=$getPos;\
         ")
     self.sel_button = QPushButton(" close")
     self.connect(self.sel_button, SIGNAL("clicked()"),lambda: self.gotoAppend())
     self.btnlayout.addWidget(self.label)
     self.btnlayout.addWidget(self.sel_button)
     self.setLayout(self.layout)
コード例 #16
0
def buildfromauto(formconfig, base):
    widgetsconfig = formconfig['widgets']

    outlayout = QFormLayout()
    outlayout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)
    outwidget = base
    outwidget.setLayout(outlayout)
    for config in widgetsconfig:
        widgettype = config['widget']
        field = config['field']
        name = config.get('name', field)
        if not field:
            utils.warning("Field can't be null for {}".format(name))
            utils.warning("Skipping widget")
            continue
        label = QLabel(name)
        label.setObjectName(field + "_label")
        widget = roam.editorwidgets.core.createwidget(widgettype, parent=base)
        widget.setObjectName(field)
        layoutwidget = QWidget()
        layoutwidget.setLayout(QBoxLayout(QBoxLayout.LeftToRight))
        layoutwidget.layout().addWidget(widget)
        if config.get('rememberlastvalue', False):
            savebutton = QToolButton()
            savebutton.setObjectName('{}_save'.format(field))
            layoutwidget.layout().addWidget(savebutton)

        outlayout.addRow(label, layoutwidget)

    outlayout.addItem(QSpacerItem(10, 10))
    installflickcharm(outwidget)
    return outwidget
コード例 #17
0
 def setupUi():
     layout = QBoxLayout(QBoxLayout.LeftToRight, self)
     layout.setContentsMargins(0, 0, 0, 0)
     self.label = QLabel('Not active debugger', self)
     layout.addWidget(self.label)
     self.btnRun = QPushButton("Run debugger", self)
     layout.addWidget(self.btnRun)
     self.setLayout(layout)
     self.btnRun.clicked.connect(self.run)
コード例 #18
0
 def __init__(self, labelText=QString(), topLeftTuple=LEFT, checked=False, parent=None):
     super(LabelledCheckBox, self).__init__(parent)
     
     self.checkBox = QCheckBox()
     self.label = QLabel(labelText)
     self.label.setBuddy(self.checkBox)
     layout = QBoxLayout(QBoxLayout.LeftToRight
             if topLeftTuple == LEFT else QBoxLayout.TopToBottom)
     layout.addWidget(self.label)
     layout.addWidget(self.checkBox)
     self.setLayout(layout)
     # Creating links to functions
     self.checkState = self.checkBox.checkState    
     self.setCheckState = self.checkBox.setCheckState    
     self.setText = self.label.setText
     self.text = self.label.text
     self.stateChanged = self.checkBox.stateChanged
コード例 #19
0
 def __init__(self, parent=None):
     super(XDockToolbar, self).__init__(parent)
     
     # defines the position for this widget
     self._currentAction = -1
     self._selectedAction = None
     self._padding = 8
     self._position = XDockToolbar.Position.South
     self._minimumPixmapSize = QSize(16, 16)
     self._maximumPixmapSize = QSize(48, 48)
     self._hoverTimer = QTimer()
     self._hoverTimer.setSingleShot(True)
     self._hoverTimer.setInterval(1000)
     self._actionHeld = False
     self._easingCurve = QEasingCurve(QEasingCurve.InOutQuad)
     self._duration = 200
     self._animating = False
     
     # install an event filter to update the location for this toolbar
     layout = QBoxLayout(QBoxLayout.LeftToRight)
     layout.setContentsMargins(2, 2, 2, 2)
     layout.setSpacing(0)
     layout.addStretch(1)
     layout.addStretch(1)
     
     self.setLayout(layout)
     self.setContentsMargins(2, 2, 2, 2)
     self.setMouseTracking(True)
     parent.window().installEventFilter(self)
     parent.window().statusBar().installEventFilter(self)
     
     self._hoverTimer.timeout.connect(self.emitActionHovered)
コード例 #20
0
ファイル: docktitlebar.py プロジェクト: mprska/ricodebug
    def __init__(self, parent):
        QToolBar.__init__(self, parent)
        assert parent
        self.dock = parent

        # a fake spacer widget
        w = QWidget(self)
        l = QHBoxLayout(w)
        l.setMargin(0)
        l.setSpacing(0)
        l.addStretch()

        frame = QFrame()
        layout = QBoxLayout(QBoxLayout.LeftToRight, frame)
        layout.setContentsMargins(4, 4, 0, 0)
        layout.setSpacing(2)
        self.aDockFrame = self.addWidget(frame)

        self.__icon = QLabel()

        layout.addWidget(self.__icon)
        layout.addWidget(QLabel(self.dock.windowTitle()))

        self.dock.windowIconChanged.connect(self.__setWindowIcon)

        # fake spacer item
        spacer = QWidgetAction(self)
        spacer.setDefaultWidget(w)

        self.setMovable(False)
        self.setFloatable(False)
        self.setIconSize(QSize(12, 12))

        self.aFloat = QAction(self)
        self.aClose = QAction(self)

        QToolBar.addAction(self, spacer)
        self.separator = QToolBar.addSeparator(self)
        QToolBar.addAction(self, self.aFloat)
        QToolBar.addAction(self, self.aClose)

        self.updateStandardIcons()

        self.dockWidgetFeaturesChanged(self.dock.features())

        self.dock.featuresChanged.connect(self.dockWidgetFeaturesChanged)
        self.aFloat.triggered.connect(self._floatTriggered)
        self.aClose.triggered.connect(self.dock.close)
コード例 #21
0
 def __init__(self, parent=None):
     super(AsyncProgressDialog, self).__init__(parent)
     self.setFixedSize(300, 40)
     self.setLayout(QBoxLayout(QBoxLayout.TopToBottom, self))
     self.progress_bar = QProgressBar(self)
     self.progress_bar.setFixedSize(280, 20)
     self.progress_bar.setMinimum(0)
     self.progress_bar.setMaximum(10)
     self.progress_bar.setTextVisible(False)
     self.layout().addWidget(self.progress_bar)
コード例 #22
0
ファイル: gui.py プロジェクト: philipstahl/emotutor
    def init_parameters(self):
        """ Creates the layout of the settings screen
        """
        layout = QGridLayout()

        label_emotions = QLabel("Emotions:")
        label_emotions.setStyleSheet("QLabel {font-weight:bold}")
        layout.addWidget(label_emotions, 0, 0)

        self.add_line(
            layout,
            [QLabel("Wasabi:"), QLabel("Marc:"), QLabel("Impulse"), QLabel("Interpolate"), QLabel("Frequence")],
            1,
        )
        self.add_line(layout, [QLabel("Happy")] + self.emo_settings["happy"], 2)
        self.add_line(layout, [QLabel("Concentrated")] + self.emo_settings["concentrated"], 3)
        self.add_line(layout, [QLabel("Bored")] + self.emo_settings["bored"], 4)
        self.add_line(layout, [QLabel("Annoyed")] + self.emo_settings["annoyed"], 5)
        self.add_line(layout, [QLabel("Angry")] + self.emo_settings["angry"], 6)
        self.add_line(layout, [QLabel("Surprise")] + self.emo_settings["surprise"], 7)

        # layout.addWidget(TestEmoButton(Happy), 2, 5)
        # layout.addWidget(TestEmoButton(Concentrated), 3, 5)
        # layout.addWidget(TestEmoButton(Bored), 4, 5)
        # layout.addWidget(TestEmoButton(Annoyed), 5, 5)
        # layout.addWidget(TestEmoButton(Angry), 6, 5)
        # layout.addWidget(TestEmoButton(Surprise), 7, 5)
        layout.addWidget(self.button("&Test", self.test_happy), 2, 5)
        layout.addWidget(self.button("&Test", self.test_concentrated), 3, 5)
        layout.addWidget(self.button("&Test", self.test_bored), 4, 5)
        layout.addWidget(self.button("&Test", self.test_annoyed), 5, 5)
        layout.addWidget(self.button("&Test", self.test_angry), 6, 5)
        layout.addWidget(self.button("&Test", self.test_surprise), 7, 5)

        emo_values = QWidget()
        emo_values.setLayout(layout)

        main_layout = QBoxLayout(2)
        main_layout.addWidget(emo_values)
        main_widget = QWidget()
        main_widget.setLayout(main_layout)
        return main_widget
コード例 #23
0
 def __init__(self, autoaccept=False, parent=None):
     """
     :param autoaccept: if True, the value of the ComboBox is immediately
     accepted after selecting it.
     """
     super(ComboBoxInputDialog, self).__init__(parent)
     self._autoaccept = autoaccept
     layout = QVBoxLayout()
     label = QtGui.QLabel()
     label.setObjectName('label')
     combobox = QtGui.QComboBox()
     combobox.setObjectName('combobox')
     combobox.activated.connect(self._combobox_activated)
     ok_button = QPushButton('OK')
     ok_button.setObjectName('ok')
     cancel_button = QPushButton('Cancel')
     cancel_button.setObjectName('cancel')
     ok_button.pressed.connect(self.accept)
     cancel_button.pressed.connect(self.reject)
     button_layout = QBoxLayout(QBoxLayout.RightToLeft)
     button_layout.addWidget(cancel_button)
     button_layout.addWidget(ok_button)
     layout.addWidget(label)
     layout.addWidget(combobox)
     layout.addLayout(button_layout)
     self.setLayout(layout)
コード例 #24
0
 def __init__(self, labelText=QString(), orientation=Qt.Horizontal,
              topLeftTuple=LEFT, parent=None):
     super(LabelledSlider, self).__init__(parent)
     
     self.labelText = labelText
     self.slider = QSlider(orientation)
     self.valueChanged = self.slider.valueChanged
     self.label = QLabel(self.labelText + ' ' + str(self.slider.value()))
     self.label.setBuddy(self.slider)
     self.slider.valueChanged.connect(self.sliderMove)
     layout = QBoxLayout(QBoxLayout.LeftToRight
             if topLeftTuple == LEFT else QBoxLayout.TopToBottom)
     layout.addWidget(self.label)
     layout.addWidget(self.slider)
     self.setLayout(layout)
     # Creating links to functions
     self.value = self.slider.value
     self.setValue = self.slider.setValue
     self.setMaximum = self.slider.setMaximum
     self.setMinimum = self.slider.setMinimum
     self.setText = self.label.setText
     self.text = self.label.text
コード例 #25
0
    def __init__(self, orientation=2, parent=None):
        QWidget.__init__(self, parent)

        self.__tabBar = QTabBar()
        self.__tabBar.setDrawBase(True)
        self.__tabBar.setShape(QTabBar.RoundedNorth)
        self.__tabBar.setFocusPolicy(Qt.NoFocus)
        self.__tabBar.setUsesScrollButtons(True)
        self.__tabBar.setElideMode(1)
        self.__stackedWidget = QStackedWidget(self)
        self.__stackedWidget.setContentsMargins(0, 0, 0, 0)
        self.barLayout = QBoxLayout(QBoxLayout.LeftToRight)
        self.barLayout.setMargin(0)
        self.layout = QBoxLayout(QBoxLayout.TopToBottom)
        self.layout.setMargin(0)
        self.layout.setSpacing(0)
        self.barLayout.addWidget(self.__tabBar)
        self.layout.addLayout(self.barLayout)
        self.layout.addWidget(self.__stackedWidget)
        self.setLayout(self.layout)

        self.__minimized = False
        self.__minSize = 0
        self.__maxSize = 0
        self.__bigSize = QSize()

        self.splitter = None

        self.__tabBar.installEventFilter(self)

        self.__orientation = orientation
        self.setOrientation(orientation)

        self.__tabBar.currentChanged.connect(
            self.__stackedWidget.setCurrentIndex)
        return
コード例 #26
0
ファイル: sidebar.py プロジェクト: eaglexmw/codimension
    def __init__( self, orientation = 2, parent = None ):
        QWidget.__init__( self, parent )

        self.__tabBar = QTabBar()
        self.__tabBar.setDrawBase( True )
        self.__tabBar.setShape( QTabBar.RoundedNorth )
        self.__tabBar.setFocusPolicy( Qt.NoFocus )
        self.__tabBar.setUsesScrollButtons( True )
        self.__tabBar.setElideMode( 1 )
        self.__stackedWidget = QStackedWidget( self )
        self.__stackedWidget.setContentsMargins( 0, 0, 0, 0 )
        self.barLayout = QBoxLayout( QBoxLayout.LeftToRight )
        self.barLayout.setMargin( 0 )
        self.layout = QBoxLayout( QBoxLayout.TopToBottom )
        self.layout.setMargin( 0 )
        self.layout.setSpacing( 0 )
        self.barLayout.addWidget( self.__tabBar )
        self.layout.addLayout( self.barLayout )
        self.layout.addWidget( self.__stackedWidget )
        self.setLayout( self.layout )

        self.__minimized = False
        self.__minSize = 0
        self.__maxSize = 0
        self.__bigSize = QSize()

        self.splitter = None

        self.__tabBar.installEventFilter( self )

        self.__orientation = orientation
        self.setOrientation( orientation )

        self.__tabBar.currentChanged.connect(
                                        self.__stackedWidget.setCurrentIndex )
        return
コード例 #27
0
 def __init__(self, labelText=QString(), position=LEFT, parent=None):
     super(LabelledTextEdit, self).__init__(parent)
     self.label = QLabel(labelText)
     self.textEdit = QTextEdit()
     self.label.setBuddy(self.textEdit)
     layout = QBoxLayout(QBoxLayout.LeftToRight if position ==
                         LEFT else QBoxLayout.TopToBottom)
     layout.addWidget(self.label)
     layout.addWidget(self.textEdit)
     self.setLayout(layout)
コード例 #28
0
ファイル: qregistry.py プロジェクト: vertrex/destruct
 def __init__(self, regf):
     QWidget.__init__(self)
     self.regf = regf
     self.keyTreeView = KeyTreeView(self, regf.key)
     self.valuesTableWidget = ValuesTableWidget(self)
     self.keyTreeView.itemClicked.connect(self.valuesTableWidget.populate)
     boxLayout = QBoxLayout(QBoxLayout.LeftToRight, self)
     boxLayout.addWidget(self.keyTreeView)
     boxLayout.addWidget(self.valuesTableWidget)
     self.setLayout(boxLayout)
コード例 #29
0
    def __init__(self, parent=None):
        super(XActionGroupWidget, self).__init__(parent)

        # define custom properties
        self._actionGroup = None
        self._padding = 5
        self._cornerRadius = 10

        # set default properties
        layout = QBoxLayout(QBoxLayout.LeftToRight)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        self.setLayout(layout)
コード例 #30
0
ファイル: TabDownloads.py プロジェクト: MaximeCheramy/pyrex
 def __init__(self, search, parent=None):
     QWidget.__init__(self, parent)
     # Load de l'UI
     PyQt4.uic.loadUi('ui/downloads.ui', self)
     # Ajout de la progressBar
     self.progressBar = QProgressBar()
     self.progressBar.setMinimum(0)
     self.progressBar.setMaximum(100)
     self.progressBar.hide()
     self.HLayout = QBoxLayout(QBoxLayout.LeftToRight)
     self.HLayout.addWidget(self.progress_label)
     self.HLayout.addWidget(self.progressBar)
     self.formLayout_3.addRow(self.HLayout)
     # Vars 
     TabDownloads.instance = self
     self.downloads        = Downloads()
     self.pos              = None
     self.download_looked  = None
     # Affichage custom
     #self.downloads_table.setStyleSheet(\
     #        "QTableView::item{ \
     #         border-right-style:solid; \
     #         border-width:0.5; \
     #         border-color: #9B9B9B; \
     #         }")
     # On autorise la creation de menu contextuel
     self.setContextMenuPolicy(Qt.CustomContextMenu)
     # Signaux
     self.customContextMenuRequested.connect(self.contextMenu)
     self.downloads_table.itemClicked.connect(self.show_info_download)
     # Init
     self.load_downloads()
     # On remove les finis et en erreur si Config.clean_dl_list = 1
     if Configuration.clean_dl_list == 1:
         self.clean_list_Action()
     #########################################################
     # On désactive les boutons qui sont pas encore implantés
     self.button_stop_all.setEnabled(False)        
     self.button_resume_all.setEnabled(False)
コード例 #31
0
class AboutWindowUI(object):
    def setupUi(self, AboutWindow):
        """GUI building for About window"""
        AboutWindow.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Expanding)
        self.centralwidget = QtGui.QWidget(AboutWindow)
        self.qbox = QBoxLayout(QBoxLayout.TopToBottom, self.centralwidget)
        self.centralwidget.setLayout(self.qbox)
        
        ###Titre###
        self.title = QtGui.QLabel(self.centralwidget)
        font = QtGui.QFont()
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        self.title.setFont(font)
        self.title.setAlignment(QtCore.Qt.AlignCenter)
        
        ###Description###
        self.description = QtGui.QLabel(self.centralwidget)
        self.description.setTextFormat(QtCore.Qt.RichText)
        self.description.setScaledContents(False)
        self.description.setWordWrap(True)
        
        ###Créateurs de l'application###
        self.creator = QtGui.QLabel(self.centralwidget)
        font = QtGui.QFont()
        font.setPointSize(10)
        self.creator.setFont(font)
        self.creator.setAlignment(QtCore.Qt.AlignCenter)
        
        ###Ajout des composants à la fenêtre principale###
        self.qbox.addWidget(self.title)
        self.qbox.addWidget(self.description)
        self.qbox.addWidget(self.creator)
        
        AboutWindow.setCentralWidget(self.centralwidget)
        
        self.retranslateUi(AboutWindow)
        QtCore.QMetaObject.connectSlotsByName(AboutWindow)


    def retranslateUi(self, AboutWindow):
        AboutWindow.setWindowTitle(_translate("AboutWindow", "A propos", None))
        self.title.setText(_translate("AboutWindow", "Candidate Crawler\n\n""Recherche ponctuelle\n", None))
        self.description.setText(_translate("AboutWindow", "<html><body><p align = justify>Ce programme parcours le site de l'APEC pour trouver les meilleurs CVs, à partir d'une liste de critères.</p><p align = justify>Une fois la recherche effectuée, l\'utilisateur télécharge un fichier Zip contenant un tableau Excel récapitulatif ainsi que les CVs trouvés.</p><p align = justify>Le programme exploite une base CSV pour stocker les CVs trouvés.</p></body></html>", None))
        self.creator.setText(_translate("AboutWindow", "<html><body><br>Application créée par Guillaume DELAMARE,</br><br>Jonathan SCHIEBEL, Julie SPENS,</br><br>Laura TAPIAS, Pierre THEILHARD</br></body><html>", None))
コード例 #32
0
 def setupUi(self, AboutWindow):
     """GUI building for About window"""
     AboutWindow.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Expanding)
     self.centralwidget = QtGui.QWidget(AboutWindow)
     self.qbox = QBoxLayout(QBoxLayout.TopToBottom, self.centralwidget)
     self.centralwidget.setLayout(self.qbox)
     
     ###Titre###
     self.title = QtGui.QLabel(self.centralwidget)
     font = QtGui.QFont()
     font.setPointSize(12)
     font.setBold(True)
     font.setWeight(75)
     self.title.setFont(font)
     self.title.setAlignment(QtCore.Qt.AlignCenter)
     
     ###Description###
     self.description = QtGui.QLabel(self.centralwidget)
     self.description.setTextFormat(QtCore.Qt.RichText)
     self.description.setScaledContents(False)
     self.description.setWordWrap(True)
     
     ###Créateurs de l'application###
     self.creator = QtGui.QLabel(self.centralwidget)
     font = QtGui.QFont()
     font.setPointSize(10)
     self.creator.setFont(font)
     self.creator.setAlignment(QtCore.Qt.AlignCenter)
     
     ###Ajout des composants à la fenêtre principale###
     self.qbox.addWidget(self.title)
     self.qbox.addWidget(self.description)
     self.qbox.addWidget(self.creator)
     
     AboutWindow.setCentralWidget(self.centralwidget)
     
     self.retranslateUi(AboutWindow)
     QtCore.QMetaObject.connectSlotsByName(AboutWindow)
コード例 #33
0
 def __init__( self, parent = None ):
     super(XSplitButton, self).__init__( parent )
     
     # define custom properties
     self._actionGroup   = QActionGroup(self)
     self._padding       = 5
     self._cornerRadius  = 10
     #self._currentAction = None
     self._checkable     = True
     
     # set default properties
     layout = QBoxLayout(QBoxLayout.LeftToRight)
     layout.setContentsMargins(0, 0, 0, 0)
     layout.setSpacing(0)
     self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
     self.setLayout(layout)
     self.clear()
     
     # create connections
     self._actionGroup.hovered.connect(self.emitHovered)
     self._actionGroup.triggered.connect(self.emitTriggered)
コード例 #34
0
ファイル: qpagewidget.py プロジェクト: pars-linux/uludag
class QPageWidget(QScrollArea):
    """ The QPageWidget provides a stack widget with animated page transitions. """
    def __init__(self, parent=None, direction="ltr", rtf=False):
        """ Creates a new QPageWidget on given parent object. 

        parent: QWidget parent
        direction: "ltr" -> Left To Right
                   "ttb" -> Top To Bottom
        rtf: Return to first, if its True it flips to the first page 
             when next page requested at the last page
        """
        # First initialize, QPageWidget is based on QScrollArea
        QScrollArea.__init__(self, parent)

        # Properties for QScrollArea
        self.setFrameShape(QFrame.NoFrame)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setWidgetResizable(True)

        # Main widget, which stores all Pages in it
        self.widget = QWidget(self)

        # Layout based on QBoxLayout which supports Vertical or Horizontal layout
        if direction == "ltr":
            self.layout = QBoxLayout(QBoxLayout.LeftToRight, self.widget)
            self.__scrollBar = self.horizontalScrollBar()
            self.__base_value = self.width
        else:
            self.layout = QBoxLayout(QBoxLayout.TopToBottom, self.widget)
            self.__scrollBar = self.verticalScrollBar()
            self.__base_value = self.height
        self.layout.setSpacing(0)
        self.layout.setMargin(0)

        # Return to first
        self.__return_to_first = rtf

        # TMP_PAGE, its using as last page in stack
        # A workaround for a QScrollArea bug
        self.__tmp_page = Page(QWidget(self.widget))
        self.__pages = [self.__tmp_page]
        self.__current = 0
        self.__last = 0

        # Set main widget
        self.setWidget(self.widget)

        # Animation TimeLine
        self.__timeline = QTimeLine()
        self.__timeline.setUpdateInterval(2)

        # Updates scrollbar position when frame changed
        self.__timeline.frameChanged.connect(
            lambda x: self.__scrollBar.setValue(x))

        # End of the animation
        self.__timeline.finished.connect(self._animateFinished)

        # Initialize animation
        self.setAnimation()
        self.setDuration()

    def _animateFinished(self):
        """ Its called by TimeLine when animation finished.

        It first runs the outMethod of last Page and then the inMethod of current Page
        Finally tt gives the focus to the current page and fixes the scrollBar
        """

        # Disable other widgets
        for page in self.__pages:
            if not page == self.__pages[self.__current]:
                page.widget.setEnabled(False)

        # Run last page's outMethod if exists
        if self.__pages[self.__last].outMethod:
            self.__pages[self.__last].outMethod()

        # Run new page's inMethod if exists
        if self.__pages[self.__current].inMethod:
            self.__pages[self.__current].inMethod()

        # Give focus to the current Page
        self.__pages[self.__current].widget.setFocus()

        # Update scrollbar position for current page
        self.__scrollBar.setValue(self.__current * self.__base_value())

        # Emit currentChanged SIGNAL
        self.emit(SIGNAL("currentChanged()"))

    def event(self, event):
        """ Overrides the main event handler to catch resize events """
        # Catch Resize event
        if event.type() == QEvent.Resize:
            # Update each page size limits to mainwidget's new size
            for page in self.__pages:
                page.widget.setMinimumSize(self.size())
                page.widget.setMaximumSize(self.size())

            # Update viewport size limits to mainwidget's new size
            # It's a workaround for QScrollArea updateGeometry bug
            self.viewport().setMinimumSize(self.size())
            self.viewport().setMaximumSize(self.size())

            # Update scrollbar position for current page
            self.__scrollBar.setValue(self.__current * self.__base_value())

        # Return the Event
        return QScrollArea.event(self, event)

    def keyPressEvent(self, event):
        """ Overrides the keyPressEvent to ignore them """
        pass

    def wheelEvent(self, event):
        """ Overrides the wheelEvent to ignore them """
        pass

    def createPage(self, widget, inMethod=None, outMethod=None):
        """ Creates and adds new Page for given widget with given in/out methods.

        widget: A QWidget which is the mainwidget for this Page
        inMethod: (optional) QPageWidget triggers this method when the Page appear
        outMethod: (optional) QPageWidget triggers this method when the Page disappear
        """
        self.addPage(Page(widget, inMethod, outMethod))

    def addPage(self, page):
        """ Adds the given Page to the stack.

        page: A Page object
        """
        # First remove the last page; its __tmp_page
        self.__pages.pop()

        # Add new page
        self.__pages.append(page)
        self.layout.addWidget(page.widget)

        # Add __tmp_page to end
        self.__pages.append(self.__tmp_page)
        self.layout.addWidget(self.__tmp_page.widget)

        # Create connections for page navigation signals from new page
        self.connect(page.widget, SIGNAL("pageNext()"), self.next)
        self.connect(page.widget, SIGNAL("pagePrevious()"), self.prev)
        self.connect(page.widget, SIGNAL("setCurrent(int)"), self.setCurrent)

    def __setCurrent(self, pageNumber):
        """ Internal method to set current page index. """
        self.__last = self.__current
        self.__current = min(max(0, pageNumber), len(self.__pages) - 2)
        if pageNumber == len(self.__pages) - 1 and self.__return_to_first:
            self.__current = 0

    def setCurrent(self, pageNumber=0):
        """ Set and flip the page with given pageNumber.

        pageNumber: index number of Page (default is 0)
        """
        self.__setCurrent(pageNumber)
        self.flipPage()

    def getCurrent(self):
        """ Returns current page index. """
        return self.__current

    def getCurrentWidget(self):
        """ Returns current page widget. """
        return self.getWidget(self.getCurrent())

    def getWidget(self, pageNumber):
        """ Returns widget for given page index 

        pageNumber: index number of Page
        """
        try:
            return self.__pages[pageNumber].widget
        except:
            return None

    def count(self):
        """ Returns number of pages. """
        return len(self.__pages) - 1

    def setAnimation(self, animation=35):
        """ Set the transition animation with the given animation.

        animation: the number represents predefined QEasingCurves
                   List of predefined QEasingCurves can be found from:
                   http://doc.qt.nokia.com/4/qeasingcurve.html#Type-enum

                   Default is QEasingCurve::InOutBack (35)
        """
        self.__animation = animation
        self.__timeline.setEasingCurve(QEasingCurve(self.__animation))

    def setDuration(self, duration=400):
        """ Set the transition duration.

        duration: duration time in ms
        """
        self.__duration = duration
        self.__timeline.setDuration(self.__duration)

    def flipPage(self, direction=0):
        """ Flip the page with given direction.

        direction: can be -1, 0 or +1
                   -1: previous page (if exists)
                    0: just flip to current page
                   +1: next page (if exists)
        """
        # Enable all widgets
        for page in self.__pages:
            page.widget.setEnabled(True)

        # Check given direction
        direction = direction if direction == 0 else max(min(1, direction), -1)

        # If direction is equal to zero no need to re-set current
        if not direction == 0:
            self.__setCurrent(self.__current + direction)

        # If last page is different from new page, flip it !
        if not self.__last == self.__current:
            self.__timeline.setFrameRange(self.__scrollBar.value(),
                                          self.__current * self.__base_value())
            self.__timeline.start()

    def next(self):
        """ Helper method to flip next page. """
        self.flipPage(1)

    def prev(self):
        """ Helper method to flip previous page. """
        self.flipPage(-1)
コード例 #35
0
ファイル: gui.py プロジェクト: philipstahl/emotutor
    def __init__(self, use_wasabi=False):
        super(AssociatedPair, self).__init__()

        # Speech recognition:
        grammar = Grammar("example grammar")
        # rules = [NumberNullRule, NumberOneRule, NumberTwoRule, NumberThreeRule,
        #         NumberFourRule, NumberFiveRule, NumberSixRule,
        #         NumberSevenRule, NumberEightRule, NumberNineRule]

        # for rule in rules:
        #    grammar.add_rule(rule(self.answer_given))

        # grammar.load()

        grammar.add_rule(NumberNullRule(self.answer_given))
        grammar.add_rule(NumberOneRule(self.answer_given))
        grammar.add_rule(NumberTwoRule(self.answer_given))
        grammar.add_rule(NumberThreeRule(self.answer_given))
        grammar.add_rule(NumberFourRule(self.answer_given))
        grammar.add_rule(NumberFiveRule(self.answer_given))
        grammar.add_rule(NumberSixRule(self.answer_given))
        grammar.add_rule(NumberSevenRule(self.answer_given))
        grammar.add_rule(NumberEightRule(self.answer_given))
        grammar.add_rule(NumberNineRule(self.answer_given))

        grammar.load()
        self.training = True

        if DEBUG:
            self.emo_output = QLabel("")
            self.cog_output = QLabel("")
            self.speech_output = QLabel("")

            agent_layout = QGridLayout()
            agent_layout.addWidget(QLabel("Emotional Output:"), 0, 0)
            agent_layout.addWidget(self.emo_output, 0, 1)
            agent_layout.addWidget(QLabel("Cognition Output:"), 1, 0)
            agent_layout.addWidget(self.cog_output, 1, 1)
            agent_layout.addWidget(QLabel("Speech Output:"), 2, 0)
            agent_layout.addWidget(self.speech_output, 2, 1)

            agent_layout.setColumnMinimumWidth(0, 100)
            agent_layout.setColumnMinimumWidth(1, 500)
            agent = QWidget()
            agent.setLayout(agent_layout)

            self.start_button = QPushButton("&Start")
            self.start_button.clicked.connect(self.start_button_clicked)

            main_layout = QBoxLayout(2)
            main_layout.addWidget(agent)
            main_layout.addWidget(self.start_button)
            self.input_widget = self.get_input_widget()
            self.input_widget.hide()
            main_layout.addWidget(self.input_widget)

            self.setLayout(main_layout)
            self.resize(600, 400)
            # 192.168.0.46
            self.exp = Environment(use_wasabi)
            self.waiting_for_answer = False

            # emotion, cog, speech = self.exp.start()
            # self.update_output(emotion, cog, speech)
            self.phase = 0
        else:
            self.speech_output = QLabel("")

            self.start_button = QPushButton("&Start")
            self.start_button.clicked.connect(self.start_button_clicked)

            main_layout = QBoxLayout(2)
            main_layout.addWidget(self.start_button)
            self.input_widget = self.get_input_widget()
            self.input_widget.hide()
            main_layout.addWidget(self.input_widget)

            self.setLayout(main_layout)
            self.resize(300, 300)
            self.width = 300
            self.height = 300
            # 192.168.0.46

            self.exp = Environment(use_wasabi)
            self.waiting_for_answer = False

            # emotion, cog, speech = self.exp.start()
            # self.update_output(emotion, cog, speech)
            self.phase = 0
            QTimer.singleShot(4000, self.second_introduction)
コード例 #36
0
ファイル: featureform.py プロジェクト: nsashi/Roam
def buildfromauto(formconfig, base):
    widgetsconfig = copy.deepcopy(formconfig['widgets'])

    try:
        widgetsconfig = base.get_widgets(widgetsconfig)
    except AttributeError:
        pass

    newstyle = formconfig.get("newstyle", False)
    hassections = any(config['widget'] == "Section" for config in widgetsconfig)

    def make_layout():
        if newstyle:
            return QVBoxLayout()
        else:
            layout = QFormLayout()
            layout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)
            return layout

    def make_tab(tabwidget, name):
        widget = QWidget()
        widget.setLayout(make_layout())
        tabwidget.addTab(widget, name)
        return widget, widget.layout()

    if hassections:
        outwidget = QTabWidget(base)
        outlayout = None
        base.setLayout(QVBoxLayout())
        base.layout().setContentsMargins(0, 0, 0, 0)
        base.layout().addWidget(outwidget)
    else:
        outwidget = base
        outlayout = make_layout()
        outwidget.setLayout(outlayout)

    if roam.config.settings.get("form_geom_edit", False):
        geomwidget = GeomWidget()
        geomwidget.setObjectName("__geomwidget")
        outlayout.addRow("Geometry", geomwidget)

    insection = False
    for config in widgetsconfig:
        widgettype = config['widget']

        ## Make the first tab if one isn't defined already and we have other sections in the config
        if not insection and hassections and not widgettype == "Section":
            name = formconfig['label']
            tabwidget, outlayout = make_tab(outwidget, name)
            insection = True

        if widgettype == 'Section':
            # Add a spacer to the last widget
            if outlayout:
                spacer = QWidget()
                spacer.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
                outlayout.addItem(QSpacerItem(10, 500))
                outlayout.addWidget(spacer)

            name = config['name']
            tabwidget, outlayout = make_tab(outwidget, name)
            installflickcharm(tabwidget)
            insection = True
            continue

        field = config['field']
        name = config.get('name', field)
        if not field:
            utils.warning("Field can't be null for {}".format(name))
            utils.warning("Skipping widget")
            continue

        label = QLabel(name)
        label.setObjectName(field + "_label")
        labelwidget = QWidget()
        labelwidget.setLayout(QBoxLayout(QBoxLayout.LeftToRight))
        labelwidget.layout().addWidget(label)
        labelwidget.layout().setContentsMargins(0, 0, 0, 0)

        widget = roam.editorwidgets.core.createwidget(widgettype, parent=base)
        widget.setObjectName(field)
        layoutwidget = QWidget()
        layoutwidget.setLayout(QBoxLayout(QBoxLayout.LeftToRight))
        layoutwidget.layout().addWidget(widget)
        layoutwidget.layout().setContentsMargins(0, 0, 0, 10)

        if config.get('rememberlastvalue', False):
            savebutton = QToolButton()
            savebutton.setObjectName('{}_save'.format(field))
            if newstyle:
                spacer = QWidget()
                spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
                labelwidget.layout().addWidget(spacer)
                labelwidget.layout().addWidget(savebutton)
            else:
                layoutwidget.layout().addWidget(savebutton)

        if newstyle:
            outlayout.addWidget(labelwidget)
            outlayout.addWidget(layoutwidget)
        else:
            outlayout.addRow(labelwidget, layoutwidget)

    spacer = QWidget()
    spacer.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
    outlayout.addWidget(spacer)
    if not hassections:
        outlayout.addItem(QSpacerItem(10, 500))
        installflickcharm(outwidget)
    return base
コード例 #37
0
 def __init__( self, orientation, parent ):
     super(XSplitterHandle, self).__init__( orientation, parent )
     
     # create a layout for the different buttons
     self._collapsed      = False
     self._storedSizes    = None
     
     self._collapseBefore = QToolButton(self)
     self._resizeGrip     = QLabel(self)
     self._collapseAfter  = QToolButton(self)
     
     self._collapseBefore.setAutoRaise(True)
     self._collapseAfter.setAutoRaise(True)
     
     self._collapseBefore.setCursor(Qt.ArrowCursor)
     self._collapseAfter.setCursor(Qt.ArrowCursor)
     
     # define the layout
     layout = QBoxLayout(QBoxLayout.LeftToRight, self)
     layout.setContentsMargins(0, 0, 0, 0)
     layout.addStretch(1)
     layout.addWidget(self._collapseBefore)
     layout.addWidget(self._resizeGrip)
     layout.addWidget(self._collapseAfter)
     layout.addStretch(1)
     self.setLayout(layout)
     
     # set the orientation to start with
     self.setOrientation(orientation)
     
     # create connections
     self._collapseAfter.clicked.connect(  self.toggleCollapseAfter )
     self._collapseBefore.clicked.connect( self.toggleCollapseBefore )
コード例 #38
0
ファイル: gui.py プロジェクト: philipstahl/emotutor
    def init_parameters(self):
        """ Creates the layout of the settings screen
        """
        main_layout = QBoxLayout(2)

        desc1 = QLabel("Intructions:")
        desc2 = QLabel("Map activation to expectation:")
        desc3 = QLabel("Map expectation to emotion:")
        desc4 = QLabel("Map expectation + answer to reaction:")
        for desc in [desc1, desc2, desc3, desc4]:
            desc.setStyleSheet("QLabel {font-weight:bold}")

        main_layout.addWidget(desc1)
        main_layout.addWidget(self.get_init_emotion_widget())
        main_layout.addWidget(desc2)
        main_layout.addWidget(self.get_function_widget())
        main_layout.addWidget(self.get_activation_widget())
        main_layout.addWidget(desc3)
        main_layout.addWidget(self.get_expectation_widget())
        main_layout.addWidget(desc4)
        main_layout.addWidget(self.get_reaction_widget())
        main_widget = QWidget()
        main_widget.setLayout(main_layout)
        return main_widget
コード例 #39
0
class E4SideBar(QWidget):
    """
    Class implementing a sidebar with a widget area, that is hidden or shown, if the
    current tab is clicked again.
    """
    Version = 1
    
    North = 0
    East  = 1
    South = 2
    West  = 3
    
    def __init__(self, orientation = None, delay = 200, parent = None):
        """
        Constructor
        
        @param orientation orientation of the sidebar widget (North, East, South, West)
        @param delay value for the expand/shrink delay in milliseconds (integer)
        @param parent parent widget (QWidget)
        """
        QWidget.__init__(self, parent)
        
        self.__tabBar = QTabBar()
        self.__tabBar.setDrawBase(True)
        self.__tabBar.setShape(QTabBar.RoundedNorth)
        self.__tabBar.setUsesScrollButtons(True)
        self.__tabBar.setDrawBase(False)
        self.__stackedWidget = QStackedWidget(self)
        self.__stackedWidget.setContentsMargins(0, 0, 0, 0)
        self.__autoHideButton = QToolButton()
        self.__autoHideButton.setCheckable(True)
        self.__autoHideButton.setIcon(UI.PixmapCache.getIcon("autoHideOff.png"))
        self.__autoHideButton.setChecked(True)
        self.__autoHideButton.setToolTip(
            self.trUtf8("Deselect to activate automatic collapsing"))
        self.barLayout = QBoxLayout(QBoxLayout.LeftToRight)
        self.barLayout.setMargin(0)
        self.layout = QBoxLayout(QBoxLayout.TopToBottom)
        self.layout.setMargin(0)
        self.layout.setSpacing(0)
        self.barLayout.addWidget(self.__autoHideButton)
        self.barLayout.addWidget(self.__tabBar)
        self.layout.addLayout(self.barLayout)
        self.layout.addWidget(self.__stackedWidget)
        self.setLayout(self.layout)
        
        # initialize the delay timer
        self.__actionMethod = None
        self.__delayTimer = QTimer(self)
        self.__delayTimer.setSingleShot(True)
        self.__delayTimer.setInterval(delay)
        self.connect(self.__delayTimer, SIGNAL("timeout()"), self.__delayedAction)
        
        self.__minimized = False
        self.__minSize = 0
        self.__maxSize = 0
        self.__bigSize = QSize()
        
        self.splitter = None
        self.splitterSizes = []
        
        self.__hasFocus = False # flag storing if this widget or any child has the focus
        self.__autoHide = False
        
        self.__tabBar.installEventFilter(self)
        
        self.__orientation = E4SideBar.North
        if orientation is None:
            orientation = E4SideBar.North
        self.setOrientation(orientation)
        
        self.connect(self.__tabBar, SIGNAL("currentChanged(int)"), 
                     self.__stackedWidget, SLOT("setCurrentIndex(int)"))
        self.connect(e4App(), SIGNAL("focusChanged(QWidget*, QWidget*)"), 
                     self.__appFocusChanged)
        self.connect(self.__autoHideButton, SIGNAL("toggled(bool)"), 
                     self.__autoHideToggled)
    
    def setSplitter(self, splitter):
        """
        Public method to set the splitter managing the sidebar.
        
        @param splitter reference to the splitter (QSplitter)
        """
        self.splitter = splitter
        self.connect(self.splitter, SIGNAL("splitterMoved(int, int)"), 
                     self.__splitterMoved)
        self.splitter.setChildrenCollapsible(False)
        index = self.splitter.indexOf(self)
        self.splitter.setCollapsible(index, False)
    
    def __splitterMoved(self, pos, index):
        """
        Private slot to react on splitter moves.
        
        @param pos new position of the splitter handle (integer)
        @param index index of the splitter handle (integer)
        """
        if self.splitter:
            self.splitterSizes = self.splitter.sizes()
    
    def __delayedAction(self):
        """
        Private slot to handle the firing of the delay timer.
        """
        if self.__actionMethod is not None:
            self.__actionMethod()
    
    def setDelay(self, delay):
        """
        Public method to set the delay value for the expand/shrink delay in milliseconds.
        
        @param delay value for the expand/shrink delay in milliseconds (integer)
        """
        self.__delayTimer.setInterval(delay)
    
    def delay(self):
        """
        Public method to get the delay value for the expand/shrink delay in milliseconds.
        
        @return value for the expand/shrink delay in milliseconds (integer)
        """
        return self.__delayTimer.interval()
    
    def __cancelDelayTimer(self):
        """
        Private method to cancel the current delay timer.
        """
        self.__delayTimer.stop()
        self.__actionMethod = None
    
    def shrink(self):
        """
        Public method to record a shrink request.
        """
        self.__delayTimer.stop()
        self.__actionMethod = self.__shrinkIt
        self.__delayTimer.start()
   
    def __shrinkIt(self):
        """
        Private method to shrink the sidebar.
        """
        self.__minimized = True
        self.__bigSize = self.size()
        if self.__orientation in [E4SideBar.North, E4SideBar.South]:
            self.__minSize = self.minimumSizeHint().height()
            self.__maxSize = self.maximumHeight()
        else:
            self.__minSize = self.minimumSizeHint().width()
            self.__maxSize = self.maximumWidth()
        if self.splitter:
            self.splitterSizes = self.splitter.sizes()
        
        self.__stackedWidget.hide()
        
        if self.__orientation in [E4SideBar.North, E4SideBar.South]:
            self.setFixedHeight(self.__tabBar.minimumSizeHint().height())
        else:
            self.setFixedWidth(self.__tabBar.minimumSizeHint().width())
        
        self.__actionMethod = None
    
    def expand(self):
        """
        Private method to record a expand request.
        """
        self.__delayTimer.stop()
        self.__actionMethod = self.__expandIt
        self.__delayTimer.start()
    
    def __expandIt(self):
        """
        Public method to expand the sidebar.
        """
        self.__minimized = False
        self.__stackedWidget.show()
        self.resize(self.__bigSize)
        if self.__orientation in [E4SideBar.North, E4SideBar.South]:
            minSize = max(self.__minSize, self.minimumSizeHint().height())
            self.setMinimumHeight(minSize)
            self.setMaximumHeight(self.__maxSize)
        else:
            minSize = max(self.__minSize, self.minimumSizeHint().width())
            self.setMinimumWidth(minSize)
            self.setMaximumWidth(self.__maxSize)
        if self.splitter:
            self.splitter.setSizes(self.splitterSizes)
        
        self.__actionMethod = None
    
    def isMinimized(self):
        """
        Public method to check the minimized state.
        
        @return flag indicating the minimized state (boolean)
        """
        return self.__minimized
    
    def isAutoHiding(self):
        """
        Public method to check, if the auto hide function is active.
        
        @return flag indicating the state of auto hiding (boolean)
        """
        return self.__autoHide
    
    def eventFilter(self, obj, evt):
        """
        Protected method to handle some events for the tabbar.
        
        @param obj reference to the object (QObject)
        @param evt reference to the event object (QEvent)
        @return flag indicating, if the event was handled (boolean)
        """
        if obj == self.__tabBar:
            if evt.type() == QEvent.MouseButtonPress:
                pos = evt.pos()
                for i in range(self.__tabBar.count()):
                    if self.__tabBar.tabRect(i).contains(pos):
                        break
                
                if i == self.__tabBar.currentIndex():
                    if self.isMinimized():
                        self.expand()
                    else:
                        self.shrink()
                    return True
                elif self.isMinimized():
                    self.expand()
            elif evt.type() == QEvent.Wheel and not self.__stackedWidget.isHidden():
                if evt.delta() > 0:
                    self.prevTab()
                else:
                    self.nextTab()
                return True
        
        return QWidget.eventFilter(self, obj, evt)
    
    def addTab(self, widget, iconOrLabel, label = None):
        """
        Public method to add a tab to the sidebar.
        
        @param widget reference to the widget to add (QWidget)
        @param iconOrLabel reference to the icon or the labeltext of the tab
            (QIcon, string or QString)
        @param label the labeltext of the tab (string or QString) (only to be
            used, if the second parameter is a QIcon)
        """
        if label:
            index = self.__tabBar.addTab(iconOrLabel, label)
            self.__tabBar.setTabToolTip(index, label)
        else:
            index = self.__tabBar.addTab(iconOrLabel)
            self.__tabBar.setTabToolTip(index, iconOrLabel)
        self.__stackedWidget.addWidget(widget)
        if self.__orientation in [E4SideBar.North, E4SideBar.South]:
            self.__minSize = self.minimumSizeHint().height()
        else:
            self.__minSize = self.minimumSizeHint().width()
    
    def insertTab(self, index, widget, iconOrLabel, label = None):
        """
        Public method to insert a tab into the sidebar.
        
        @param index the index to insert the tab at (integer)
        @param widget reference to the widget to insert (QWidget)
        @param iconOrLabel reference to the icon or the labeltext of the tab
            (QIcon, string or QString)
        @param label the labeltext of the tab (string or QString) (only to be
            used, if the second parameter is a QIcon)
        """
        if label:
            index = self.__tabBar.insertTab(index, iconOrLabel, label)
            self.__tabBar.setTabToolTip(index, label)
        else:
            index = self.__tabBar.insertTab(index, iconOrLabel)
            self.__tabBar.setTabToolTip(index, iconOrLabel)
        self.__stackedWidget.insertWidget(index, widget)
        if self.__orientation in [E4SideBar.North, E4SideBar.South]:
            self.__minSize = self.minimumSizeHint().height()
        else:
            self.__minSize = self.minimumSizeHint().width()
    
    def removeTab(self, index):
        """
        Public method to remove a tab.
        
        @param index the index of the tab to remove (integer)
        """
        self.__stackedWidget.removeWidget(self.__stackedWidget.widget(index))
        self.__tabBar.removeTab(index)
        if self.__orientation in [E4SideBar.North, E4SideBar.South]:
            self.__minSize = self.minimumSizeHint().height()
        else:
            self.__minSize = self.minimumSizeHint().width()
    
    def clear(self):
        """
        Public method to remove all tabs.
        """
        while self.count() > 0:
            self.removeTab(0)
    
    def prevTab(self):
        """
        Public slot used to show the previous tab.
        """
        ind = self.currentIndex() - 1
        if ind == -1:
            ind = self.count() - 1
            
        self.setCurrentIndex(ind)
        self.currentWidget().setFocus()
    
    def nextTab(self):
        """
        Public slot used to show the next tab.
        """
        ind = self.currentIndex() + 1
        if ind == self.count():
            ind = 0
            
        self.setCurrentIndex(ind)
        self.currentWidget().setFocus()
    
    def count(self):
        """
        Public method to get the number of tabs.
        
        @return number of tabs in the sidebar (integer)
        """
        return self.__tabBar.count()
    
    def currentIndex(self):
        """
        Public method to get the index of the current tab.
        
        @return index of the current tab (integer)
        """
        return self.__stackedWidget.currentIndex()
    
    def setCurrentIndex(self, index):
        """
        Public slot to set the current index.
        
        @param index the index to set as the current index (integer)
        """
        self.__tabBar.setCurrentIndex(index)
        self.__stackedWidget.setCurrentIndex(index)
        if self.isMinimized():
            self.expand()
    
    def currentWidget(self):
        """
        Public method to get a reference to the current widget.
        
        @return reference to the current widget (QWidget)
        """
        return self.__stackedWidget.currentWidget()
    
    def setCurrentWidget(self, widget):
        """
        Public slot to set the current widget.
        
        @param widget reference to the widget to become the current widget (QWidget)
        """
        self.__stackedWidget.setCurrentWidget(widget)
        self.__tabBar.setCurrentIndex(self.__stackedWidget.currentIndex())
        if self.isMinimized():
            self.expand()
    
    def indexOf(self, widget):
        """
        Public method to get the index of the given widget.
        
        @param widget reference to the widget to get the index of (QWidget)
        @return index of the given widget (integer)
        """
        return self.__stackedWidget.indexOf(widget)
    
    def isTabEnabled(self, index):
        """
        Public method to check, if a tab is enabled.
        
        @param index index of the tab to check (integer)
        @return flag indicating the enabled state (boolean)
        """
        return self.__tabBar.isTabEnabled(index)
    
    def setTabEnabled(self, index, enabled):
        """
        Public method to set the enabled state of a tab.
        
        @param index index of the tab to set (integer)
        @param enabled enabled state to set (boolean)
        """
        self.__tabBar.setTabEnabled(index, enabled)
    
    def orientation(self):
        """
        Public method to get the orientation of the sidebar.
        
        @return orientation of the sidebar (North, East, South, West)
        """
        return self.__orientation
    
    def setOrientation(self, orient):
        """
        Public method to set the orientation of the sidebar.
        @param orient orientation of the sidebar (North, East, South, West)
        """
        if orient == E4SideBar.North:
            self.__tabBar.setShape(QTabBar.RoundedNorth)
            self.__tabBar.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
            self.barLayout.setDirection(QBoxLayout.LeftToRight)
            self.layout.setDirection(QBoxLayout.TopToBottom)
            self.layout.setAlignment(self.barLayout, Qt.AlignLeft)
        elif orient == E4SideBar.East:
            self.__tabBar.setShape(QTabBar.RoundedEast)
            self.__tabBar.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding)
            self.barLayout.setDirection(QBoxLayout.TopToBottom)
            self.layout.setDirection(QBoxLayout.RightToLeft)
            self.layout.setAlignment(self.barLayout, Qt.AlignTop)
        elif orient == E4SideBar.South:
            self.__tabBar.setShape(QTabBar.RoundedSouth)
            self.__tabBar.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
            self.barLayout.setDirection(QBoxLayout.LeftToRight)
            self.layout.setDirection(QBoxLayout.BottomToTop)
            self.layout.setAlignment(self.barLayout, Qt.AlignLeft)
        elif orient == E4SideBar.West:
            self.__tabBar.setShape(QTabBar.RoundedWest)
            self.__tabBar.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding)
            self.barLayout.setDirection(QBoxLayout.TopToBottom)
            self.layout.setDirection(QBoxLayout.LeftToRight)
            self.layout.setAlignment(self.barLayout, Qt.AlignTop)
        self.__orientation = orient
    
    def tabIcon(self, index):
        """
        Public method to get the icon of a tab.
        
        @param index index of the tab (integer)
        @return icon of the tab (QIcon)
        """
        return self.__tabBar.tabIcon(index)
    
    def setTabIcon(self, index, icon):
        """
        Public method to set the icon of a tab.
        
        @param index index of the tab (integer)
        @param icon icon to be set (QIcon)
        """
        self.__tabBar.setTabIcon(index, icon)
    
    def tabText(self, index):
        """
        Public method to get the text of a tab.
        
        @param index index of the tab (integer)
        @return text of the tab (QString)
        """
        return self.__tabBar.tabText(index)
    
    def setTabText(self, index, text):
        """
        Public method to set the text of a tab.
        
        @param index index of the tab (integer)
        @param text text to set (QString)
        """
        self.__tabBar.setTabText(index, text)
    
    def tabToolTip(self, index):
        """
        Public method to get the tooltip text of a tab.
        
        @param index index of the tab (integer)
        @return tooltip text of the tab (QString)
        """
        return self.__tabBar.tabToolTip(index)
    
    def setTabToolTip(self, index, tip):
        """
        Public method to set the tooltip text of a tab.
        
        @param index index of the tab (integer)
        @param tooltip text text to set (QString)
        """
        self.__tabBar.setTabToolTip(index, tip)
    
    def tabWhatsThis(self, index):
        """
        Public method to get the WhatsThis text of a tab.
        
        @param index index of the tab (integer)
        @return WhatsThis text of the tab (QString)
        """
        return self.__tabBar.tabWhatsThis(index)
    
    def setTabWhatsThis(self, index, text):
        """
        Public method to set the WhatsThis text of a tab.
        
        @param index index of the tab (integer)
        @param WhatsThis text text to set (QString)
        """
        self.__tabBar.setTabWhatsThis(index, text)
    
    def widget(self, index):
        """
        Public method to get a reference to the widget associated with a tab.
        
        @param index index of the tab (integer)
        @return reference to the widget (QWidget)
        """
        return self.__stackedWidget.widget(index)
    
    def saveState(self):
        """
        Public method to save the state of the sidebar.
        
        @return saved state as a byte array (QByteArray)
        """
        if len(self.splitterSizes) == 0:
            if self.splitter:
                self.splitterSizes = self.splitter.sizes()
            self.__bigSize = self.size()
            if self.__orientation in [E4SideBar.North, E4SideBar.South]:
                self.__minSize = self.minimumSizeHint().height()
                self.__maxSize = self.maximumHeight()
            else:
                self.__minSize = self.minimumSizeHint().width()
                self.__maxSize = self.maximumWidth()
        
        data = QByteArray()
        stream = QDataStream(data, QIODevice.WriteOnly)
        
        stream.writeUInt16(self.Version)
        stream.writeBool(self.__minimized)
        stream << self.__bigSize
        stream.writeUInt16(self.__minSize)
        stream.writeUInt16(self.__maxSize)
        stream.writeUInt16(len(self.splitterSizes))
        for size in self.splitterSizes:
            stream.writeUInt16(size)
        stream.writeBool(self.__autoHide)
        
        return data
    
    def restoreState(self, state):
        """
        Public method to restore the state of the sidebar.
        
        @param state byte array containing the saved state (QByteArray)
        @return flag indicating success (boolean)
        """
        if state.isEmpty():
            return False
        
        if self.__orientation in [E4SideBar.North, E4SideBar.South]:
            minSize = self.layout.minimumSize().height()
            maxSize = self.maximumHeight()
        else:
            minSize = self.layout.minimumSize().width()
            maxSize = self.maximumWidth()
        
        data = QByteArray(state)
        stream = QDataStream(data, QIODevice.ReadOnly)
        stream.readUInt16()  # version
        minimized = stream.readBool()
        
        if minimized:
            self.shrink()
        
        stream >> self.__bigSize
        self.__minSize = max(stream.readUInt16(), minSize)
        self.__maxSize = max(stream.readUInt16(), maxSize)
        count = stream.readUInt16()
        self.splitterSizes = []
        for i in range(count):
            self.splitterSizes.append(stream.readUInt16())
        
        self.__autoHide = stream.readBool()
        self.__autoHideButton.setChecked(not self.__autoHide)
        
        if not minimized:
            self.expand()
        
        return True
    
    #######################################################################
    ## methods below implement the autohide functionality
    #######################################################################
    
    def __autoHideToggled(self, checked):
        """
        Private slot to handle the toggling of the autohide button.
        
        @param checked flag indicating the checked state of the button (boolean)
        """
        self.__autoHide = not checked
        if self.__autoHide:
            self.__autoHideButton.setIcon(UI.PixmapCache.getIcon("autoHideOn.png"))
        else:
            self.__autoHideButton.setIcon(UI.PixmapCache.getIcon("autoHideOff.png"))
    
    def __appFocusChanged(self, old, now):
        """
        Private slot to handle a change of the focus.
        
        @param old reference to the widget, that lost focus (QWidget or None)
        @param now reference to the widget having the focus (QWidget or None)
        """
        self.__hasFocus = self.isAncestorOf(now)
        if self.__autoHide and not self.__hasFocus and not self.isMinimized():
            self.shrink()
        elif self.__autoHide and self.__hasFocus and self.isMinimized():
            self.expand()
    
    def enterEvent(self, event):
        """
        Protected method to handle the mouse entering this widget.
        
        @param event reference to the event (QEvent)
        """
        if self.__autoHide and self.isMinimized():
            self.expand()
        else:
            self.__cancelDelayTimer()
    
    def leaveEvent(self, event):
        """
        Protected method to handle the mouse leaving this widget.
        
        @param event reference to the event (QEvent)
        """
        if self.__autoHide and not self.__hasFocus and not self.isMinimized():
            self.shrink()
        else:
            self.__cancelDelayTimer()
    
    def shutdown(self):
        """
        Public method to shut down the object.
        
        This method does some preparations so the object can be deleted properly.
        It disconnects from the focusChanged signal in order to avoid trouble later
        on.
        """
        self.disconnect(e4App(), SIGNAL("focusChanged(QWidget*, QWidget*)"), 
                        self.__appFocusChanged)
コード例 #40
0
class SideBar(QWidget):
    """ Sidebar with a widget area which is hidden or shown.
        On by clicking any tab, off by clicking the current tab.
    """

    North = 0
    East = 1
    South = 2
    West = 3

    def __init__(self, orientation=2, parent=None):
        QWidget.__init__(self, parent)

        self.__tabBar = QTabBar()
        self.__tabBar.setDrawBase(True)
        self.__tabBar.setShape(QTabBar.RoundedNorth)
        self.__tabBar.setFocusPolicy(Qt.NoFocus)
        self.__tabBar.setUsesScrollButtons(True)
        self.__tabBar.setElideMode(1)
        self.__stackedWidget = QStackedWidget(self)
        self.__stackedWidget.setContentsMargins(0, 0, 0, 0)
        self.barLayout = QBoxLayout(QBoxLayout.LeftToRight)
        self.barLayout.setMargin(0)
        self.layout = QBoxLayout(QBoxLayout.TopToBottom)
        self.layout.setMargin(0)
        self.layout.setSpacing(0)
        self.barLayout.addWidget(self.__tabBar)
        self.layout.addLayout(self.barLayout)
        self.layout.addWidget(self.__stackedWidget)
        self.setLayout(self.layout)

        self.__minimized = False
        self.__minSize = 0
        self.__maxSize = 0
        self.__bigSize = QSize()

        self.splitter = None

        self.__tabBar.installEventFilter(self)

        self.__orientation = orientation
        self.setOrientation(orientation)

        self.__tabBar.currentChanged.connect(
            self.__stackedWidget.setCurrentIndex)
        return

    def setSplitter(self, splitter):
        """ Set the splitter managing the sidebar """
        self.splitter = splitter
        return

    def __getIndex(self):
        " Provides the widget index in splitters "
        if self.__orientation == SideBar.West:
            return 0
        if self.__orientation == SideBar.East:
            return 2
        if self.__orientation == SideBar.South:
            return 1
        return 0

    def __getWidget(self):
        " Provides a reference to the widget "
        return self.splitter.widget(self.__getIndex())

    def shrink(self):
        """ Shrink the sidebar """
        if self.__minimized:
            return

        self.__minimized = True
        self.__bigSize = self.size()
        if self.__orientation in [SideBar.North, SideBar.South]:
            self.__minSize = self.minimumHeight()
            self.__maxSize = self.maximumHeight()
        else:
            self.__minSize = self.minimumWidth()
            self.__maxSize = self.maximumWidth()

        self.__stackedWidget.hide()

        sizes = self.splitter.sizes()
        selfIndex = self.__getIndex()

        if self.__orientation in [SideBar.North, SideBar.South]:
            newHeight = self.__tabBar.minimumSizeHint().height()
            self.setFixedHeight(newHeight)

            diff = sizes[selfIndex] - newHeight
            sizes[selfIndex] = newHeight
        else:
            newWidth = self.__tabBar.minimumSizeHint().width()
            self.setFixedWidth(newWidth)

            diff = sizes[selfIndex] - newWidth
            sizes[selfIndex] = newWidth

        if selfIndex == 0:
            sizes[1] += diff
        else:
            sizes[selfIndex - 1] += diff

        self.splitter.setSizes(sizes)
        return

    def expand(self):
        """ Expand the sidebar """
        if not self.__minimized:
            return

        self.__minimized = False
        self.__stackedWidget.show()
        self.resize(self.__bigSize)

        sizes = self.splitter.sizes()
        selfIndex = self.__getIndex()

        if self.__orientation in [SideBar.North, SideBar.South]:
            self.setMinimumHeight(self.__minSize)
            self.setMaximumHeight(self.__maxSize)

            diff = self.__bigSize.height() - sizes[selfIndex]
            sizes[selfIndex] = self.__bigSize.height()
        else:
            self.setMinimumWidth(self.__minSize)
            self.setMaximumWidth(self.__maxSize)

            diff = self.__bigSize.width() - sizes[selfIndex]
            sizes[selfIndex] = self.__bigSize.width()

        if selfIndex == 0:
            sizes[1] -= diff
        else:
            sizes[selfIndex - 1] -= diff

        self.splitter.setSizes(sizes)
        return

    def isMinimized(self):
        """ Provides the minimized state """
        return self.__minimized

    def eventFilter(self, obj, evt):
        """ Handle click events for the tabbar """

        if obj == self.__tabBar:
            if evt.type() == QEvent.MouseButtonPress:
                pos = evt.pos()

                index = self.__tabBar.count() - 1
                while index >= 0:
                    if self.__tabBar.tabRect(index).contains(pos):
                        break
                    index -= 1

                if index == self.__tabBar.currentIndex():
                    if self.isMinimized():
                        self.expand()
                    else:
                        self.shrink()
                    return True

                elif self.isMinimized():
                    if self.isTabEnabled(index):
                        self.expand()

        return QWidget.eventFilter(self, obj, evt)

    def addTab(self, widget, iconOrLabel, label=None):
        """ Add a tab to the sidebar """

        if label:
            self.__tabBar.addTab(iconOrLabel, label)
        else:
            self.__tabBar.addTab(iconOrLabel)
        self.__stackedWidget.addWidget(widget)
        return

    def insertTab(self, index, widget, iconOrLabel, label=None):
        """ Insert a tab into the sidebar """

        if label:
            self.__tabBar.insertTab(index, iconOrLabel, label)
        else:
            self.__tabBar.insertTab(index, iconOrLabel)
        self.__stackedWidget.insertWidget(index, widget)
        return

    def removeTab(self, index):
        """ Remove a tab """

        self.__stackedWidget.removeWidget(self.__stackedWidget.widget(index))
        self.__tabBar.removeTab(index)
        return

    def clear(self):
        """ Remove all tabs """

        while self.count() > 0:
            self.removeTab(0)
        return

    def prevTab(self):
        """ Show the previous tab """

        index = self.currentIndex() - 1
        if index < 0:
            index = self.count() - 1

        self.setCurrentIndex(index)
        self.currentWidget().setFocus()
        return

    def nextTab(self):
        """ Show the next tab """

        index = self.currentIndex() + 1
        if index >= self.count():
            index = 0

        self.setCurrentIndex(index)
        self.currentWidget().setFocus()
        return

    def count(self):
        """ Provides the number of tabs """

        return self.__tabBar.count()

    def currentIndex(self):
        """ Provides the index of the current tab """

        return self.__stackedWidget.currentIndex()

    def setCurrentIndex(self, index):
        """ Switch to the certain tab """

        if index >= self.currentIndex():
            return

        self.__tabBar.setCurrentIndex(index)
        self.__stackedWidget.setCurrentIndex(index)
        if self.isMinimized():
            self.expand()
        return

    def currentWidget(self):
        """ Provide a reference to the current widget """

        return self.__stackedWidget.currentWidget()

    def setCurrentWidget(self, widget):
        """ Set the current widget """

        self.__stackedWidget.setCurrentWidget(widget)
        self.__tabBar.setCurrentIndex(self.__stackedWidget.currentIndex())
        if self.isMinimized():
            self.expand()
        return

    def indexOf(self, widget):
        """ Provides the index of the given widget """

        return self.__stackedWidget.indexOf(widget)

    def isTabEnabled(self, index):
        """ Check if the tab is enabled """

        return self.__tabBar.isTabEnabled(index)

    def setTabEnabled(self, index, enabled):
        """ Set the enabled state of the tab """

        self.__tabBar.setTabEnabled(index, enabled)
        return

    def orientation(self):
        """ Provides the orientation of the sidebar """

        return self.__orientation

    def setOrientation(self, orient):
        """ Set the orientation of the sidebar """

        if orient == SideBar.North:
            self.__tabBar.setShape(QTabBar.RoundedNorth)
            self.barLayout.setDirection(QBoxLayout.LeftToRight)
            self.layout.setDirection(QBoxLayout.TopToBottom)
            self.layout.setAlignment(self.barLayout, Qt.AlignLeft)
        elif orient == SideBar.East:
            self.__tabBar.setShape(QTabBar.RoundedEast)
            self.barLayout.setDirection(QBoxLayout.TopToBottom)
            self.layout.setDirection(QBoxLayout.RightToLeft)
            self.layout.setAlignment(self.barLayout, Qt.AlignTop)
        elif orient == SideBar.South:
            self.__tabBar.setShape(QTabBar.RoundedSouth)
            self.barLayout.setDirection(QBoxLayout.LeftToRight)
            self.layout.setDirection(QBoxLayout.BottomToTop)
            self.layout.setAlignment(self.barLayout, Qt.AlignLeft)
        else:
            # default
            orient = SideBar.West
            self.__tabBar.setShape(QTabBar.RoundedWest)
            self.barLayout.setDirection(QBoxLayout.TopToBottom)
            self.layout.setDirection(QBoxLayout.LeftToRight)
            self.layout.setAlignment(self.barLayout, Qt.AlignTop)
        self.__orientation = orient
        return

    def tabIcon(self, index):
        """ Provide the icon of the tab """

        return self.__tabBar.tabIcon(index)

    def setTabIcon(self, index, icon):
        """ Set the icon of the tab """

        self.__tabBar.setTabIcon(index, icon)
        return

    def tabText(self, index):
        """ Provide the text of the tab """

        return self.__tabBar.tabText(index)

    def setTabText(self, index, text):
        """ Set the text of the tab """

        self.__tabBar.setTabText(index, text)
        return

    def tabToolTip(self, index):
        """ Provide the tooltip text of the tab """

        return self.__tabBar.tabToolTip(index)

    def setTabToolTip(self, index, tip):
        """ Set the tooltip text of the tab """

        self.__tabBar.setTabToolTip(index, tip)
        return

    def tabWhatsThis(self, index):
        """ Provide the WhatsThis text of the tab """

        return self.__tabBar.tabWhatsThis(index)

    def setTabWhatsThis(self, index, text):
        """ Set the WhatsThis text for the tab """

        self.__tabBar.setTabWhatsThis(index, text)
        return

    def widget(self, index):
        """ Provides the reference to the widget (QWidget) """

        return self.__stackedWidget.widget(index)
コード例 #41
0
    #ssdp.search()
    #ssdp.search(addr=('192.168.0.114', 1900))

    widget = QWidget()
    widget.setWindowTitle("SSDP Client/Server")
    widget.setVisible(True)

    closeButton = QPushButton("Zamknij")
    closeButton.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
    QWidget.connect(closeButton, SIGNAL("clicked()"), upnpy.qtApp.quit)

    searchButton = QPushButton("Search")
    QWidget.connect(searchButton, SIGNAL("clicked()"), search)

    adButton = QPushButton('Advertise Device')
    QWidget.connect(adButton, SIGNAL('clicked()'), advertise)

    global edit
    edit.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

    layout = QBoxLayout(QBoxLayout.TopToBottom)
    layout.addWidget(edit, 3)
    layout.addWidget(searchButton)
    layout.addWidget(adButton)
    layout.addWidget(closeButton)
    widget.setLayout(layout)

    upnpy.run()
    print "Zamykam aplikacje"
コード例 #42
0
 def __init__(self, orientation = None, delay = 200, parent = None):
     """
     Constructor
     
     @param orientation orientation of the sidebar widget (North, East, South, West)
     @param delay value for the expand/shrink delay in milliseconds (integer)
     @param parent parent widget (QWidget)
     """
     QWidget.__init__(self, parent)
     
     self.__tabBar = QTabBar()
     self.__tabBar.setDrawBase(True)
     self.__tabBar.setShape(QTabBar.RoundedNorth)
     self.__tabBar.setUsesScrollButtons(True)
     self.__tabBar.setDrawBase(False)
     self.__stackedWidget = QStackedWidget(self)
     self.__stackedWidget.setContentsMargins(0, 0, 0, 0)
     self.__autoHideButton = QToolButton()
     self.__autoHideButton.setCheckable(True)
     self.__autoHideButton.setIcon(UI.PixmapCache.getIcon("autoHideOff.png"))
     self.__autoHideButton.setChecked(True)
     self.__autoHideButton.setToolTip(
         self.trUtf8("Deselect to activate automatic collapsing"))
     self.barLayout = QBoxLayout(QBoxLayout.LeftToRight)
     self.barLayout.setMargin(0)
     self.layout = QBoxLayout(QBoxLayout.TopToBottom)
     self.layout.setMargin(0)
     self.layout.setSpacing(0)
     self.barLayout.addWidget(self.__autoHideButton)
     self.barLayout.addWidget(self.__tabBar)
     self.layout.addLayout(self.barLayout)
     self.layout.addWidget(self.__stackedWidget)
     self.setLayout(self.layout)
     
     # initialize the delay timer
     self.__actionMethod = None
     self.__delayTimer = QTimer(self)
     self.__delayTimer.setSingleShot(True)
     self.__delayTimer.setInterval(delay)
     self.connect(self.__delayTimer, SIGNAL("timeout()"), self.__delayedAction)
     
     self.__minimized = False
     self.__minSize = 0
     self.__maxSize = 0
     self.__bigSize = QSize()
     
     self.splitter = None
     self.splitterSizes = []
     
     self.__hasFocus = False # flag storing if this widget or any child has the focus
     self.__autoHide = False
     
     self.__tabBar.installEventFilter(self)
     
     self.__orientation = E4SideBar.North
     if orientation is None:
         orientation = E4SideBar.North
     self.setOrientation(orientation)
     
     self.connect(self.__tabBar, SIGNAL("currentChanged(int)"), 
                  self.__stackedWidget, SLOT("setCurrentIndex(int)"))
     self.connect(e4App(), SIGNAL("focusChanged(QWidget*, QWidget*)"), 
                  self.__appFocusChanged)
     self.connect(self.__autoHideButton, SIGNAL("toggled(bool)"), 
                  self.__autoHideToggled)
コード例 #43
0
 def layoutWidgets(self):
     layout = QBoxLayout(QBoxLayout.TopToBottom)
     layout.addWidget(self.keySequenceLabel)
     layout.addWidget(self.keySequenceLineEdit)
     layout.addWidget(self.keySequenceButtonBox)
     self.setLayout(layout)
コード例 #44
0
 def __init__(self, parent=None):
     super(urlgroup, self).__init__(parent)
     self.setGeometry(10, 30, 500, 80)
     self.setObjectName('urlgroup')
     self.urlbar = QLineEdit()
     self.urlbar.setObjectName('urlbar')
     self.urlbar.setText('Collez votre URL i�i')
     self.urlbar.setStyleSheet('font-weight:lighter;color:gray;')
     self.urlbar.show()
     self.parsebutton = QPushButton('Go !!')
     self.parsebutton.setObjectName('parsebutton')
     self.parsebutton.show()
     layout = QBoxLayout(QBoxLayout.LeftToRight, self)
     layout.addWidget(self.urlbar)
     layout.addWidget(self.parsebutton)
     self.show()
     self.group2 = QGroupBox(parent)
     self.group2.setObjectName('core')
     self.group2.setGeometry(10, 120, 500, 280)
     self.group2.show()
     self.group3 = QGroupBox(self.group2)
     self.group3.setObjectName('albuminfos')
     self.group3.setGeometry(10, 15, 200, 245)
     self.group3.show()
     self.itemlist = QListWidget(self.group2)
     self.itemlist.setGeometry(250, 15, 230, 245)
     self.itemlist.show()
     self.dlgroup = QGroupBox(parent)
     self.dlgroup.setObjectName('dlgroup')
     self.dlgroup.setGeometry(10, 420, 500, 100)
     self.dlgroup.show()
     self.dlgroup.dlbutton = QPushButton('Download', self.dlgroup)
     self.dlgroup.dlbutton.setObjectName('dlbutton')
     self.dlgroup.dlbutton.move(10, 20)
     self.dlgroup.dlbutton.show()
     self.dlgroup.progressbar = QProgressBar(self.dlgroup)
     self.dlgroup.progressbar.setObjectName('progressbar')
     self.dlgroup.progressbar.setGeometry(100, 21, 380, 21)
     self.dlgroup.progressbar.show()
     self.dlgroup.dlinfos = QLabel(self.dlgroup)
     self.dlgroup.dlinfos.setGeometry(100, 70, 200, 21)
     self.dlgroup.dlinfos.show()
     self.dlgroup.dledfile = QLabel(self.dlgroup)
     self.dlgroup.dledfile.setGeometry(300, 70, 200, 21)
     self.dlgroup.dledfile.show()
     self.dlgroup.dlto = QLineEdit('C:\\', self.dlgroup)
     self.dlgroup.dlto.setGeometry(100, 50, 350, 21)
     self.dlgroup.dlto.show()
     self.dlgroup.dlto.changebt = QToolButton(self.dlgroup)
     self.dlgroup.dlto.changebt.setObjectName('dltobt')
     self.dlgroup.dlto.changebt.setGeometry(10, 50, 75, 21)
     self.dlgroup.dlto.changebt.setText('To')
     self.dlgroup.dlto.changebt.show()
     self.dlgroup.dlto.openf = QPushButton('Open', self.dlgroup)
     self.dlgroup.dlto.openf.setGeometry(455, 50, 35, 21)
     self.dlgroup.dlto.openf.setObjectName('openfolder')
     self.dlgroup.dlto.openf.show()
     self.album = QLabel(self.group3)
     self.artist = QLabel(self.group3)
     self.year = QLabel(self.group3)
     self.tracks = QLabel(self.group3)
     self.coverart = QLabel(self.group3)
     self.urlbar.setFocus(True)
     self.connect(self.parsebutton, SIGNAL('clicked()'), self.parseclicked)
     self.connect(self.dlgroup.dlbutton, SIGNAL('clicked()'), self.launchdl)
     self.connect(self.dlgroup.dlto.changebt, SIGNAL('clicked()'),
                  self.changedir)
     self.connect(self.dlgroup.dlto.openf, SIGNAL('clicked()'),
                  self.openfolder)
コード例 #45
0
ファイル: dbus_denemesi.py プロジェクト: pars-linux/uludag
class MainWindow (QWidget):
    def __init__ (self):
        QWidget.__init__ (self)
        

        self.sessionBus = dbus.SessionBus()
        self.systemBus = dbus.SystemBus()
        
        self.powerdevil = self.sessionBus.get_object('org.kde.screensaver', '/App') 
        self.powerdevil2 = self.sessionBus.get_object('org.kde.screensaver', '/ScreenSaver') 
        #self.powerdevil3 = self.sessionBus.get_object('org.kde.kopete', '/Kopete') 
        #self.powerdevil4 = self.sessionBus.get_object('org.kde.kopete', '/Kopete') 
        #self.powerdevil5 = self.sessionBus.get_object('org.kde.kopete', '/Kopete') 
        self.powerdevil6 = self.sessionBus.get_object('org.kde.plasma-desktop', '/App') 
        #self.powerdevil7 = self.sessionBus.get_object('org.kde.yakuake', '/yakuake/MainWindow_1') 
        #self.powerdevil8 = self.sessionBus.get_object('org.kde.amarok', '/Player') 
        #self.sistemeGonder=self.systemBus.get_object('tr.org.pardus.comar','/package/iptables')
        self.sistemeGonder=self.systemBus.get_object('tr.org.pardus.comar','/package/openssh')
        
        
        self.layout = QBoxLayout(QBoxLayout.TopToBottom, self)
        self.setLayout(self.layout)
        
        label = QLabel ("bir program", self)
        self.layout.addWidget(label)
 
	button0 = QPushButton("comarrr!", self)
        self.layout.addWidget(button0)
        button = QPushButton("yazdir!", self)
        self.layout.addWidget(button)
        button2 = QPushButton("ekrani kilitle!", self)
        self.layout.addWidget(button2)
        button3 = QPushButton("kopete baglantisini kes!", self)
        self.layout.addWidget(button3)
        button4 = QPushButton("canerle sohbet baslat!", self)
        self.layout.addWidget(button4)
        button6 = QPushButton("dashboardı goster!", self)
        self.layout.addWidget(button6)
        button7 = QPushButton("yakuake yi toogle et!", self)
        self.layout.addWidget(button7)
        button8 = QPushButton("amarok baslat/duraklat!", self)
        self.layout.addWidget(button8)
 
	QObject.connect(button0, SIGNAL("clicked()"), self.screenOff0)
        QObject.connect(button, SIGNAL("clicked()"), self.screenOff)
        QObject.connect(button2, SIGNAL("clicked()"), self.screenOff2)
        QObject.connect(button3, SIGNAL("clicked()"), self.screenOff3)
        QObject.connect(button4, SIGNAL("clicked()"), self.screenOff4)
        QObject.connect(button6, SIGNAL("clicked()"), self.screenOff6)
        QObject.connect(button7, SIGNAL("clicked()"), self.screenOff7)
        QObject.connect(button8, SIGNAL("clicked()"), self.screenOff8)
        
        self.resize (640, 480)
 
    def screenOff(self):
        self.powerdevil.showTaskManager(dbus_interface='org.kde.krunner.App')
    def screenOff2(self):
        self.powerdevil2.Lock(dbus_interface='org.freedesktop.ScreenSaver')
    def screenOff3(self):
        self.powerdevil3.disconnectAll(dbus_interface='org.kde.Kopete')
    def screenOff4(self):
        self.powerdevil3.openChat("*****@*****.**", dbus_interface='org.kde.Kopete')
    def screenOff6(self):
        self.powerdevil6.showDashboard(True, dbus_interface='local.PlasmaApp')
    def screenOff7(self):
        self.powerdevil7.toggleWindowState(dbus_interface='org.kde.yakuake')
    def screenOff8(self):
        self.powerdevil8.PlayPause(dbus_interface='org.freedesktop.MediaPlayer')
    def screenOff0(self):
	#self.sistemeGonder.start(dbus_interface='tr.pardus.comar.System.Service')
	self.sistemeGonder.start(dbus_interface='tr.pardus.comar.System.Service')
コード例 #46
0
ファイル: gui.py プロジェクト: skudervatchi/Dzik
 def __init__(self, parent=None):
     super(urlgroup, self).__init__(parent)
     self.setGeometry(10,30,500,80)
     self.setObjectName('urlgroup')
     self.urlbar = QLineEdit()
     self.urlbar.setObjectName('urlbar')
     self.urlbar.setText('Collez votre URL içi')
     self.urlbar.setStyleSheet('font-weight:lighter;color:gray;')
     self.urlbar.show()
     self.parsebutton = QPushButton('Go !!')
     self.parsebutton.setObjectName('parsebutton')
     self.parsebutton.show()
     layout = QBoxLayout(QBoxLayout.LeftToRight, self)
     layout.addWidget(self.urlbar)
     layout.addWidget(self.parsebutton)
     self.show()
     self.group2 = QGroupBox(parent)
     self.group2.setObjectName('core')
     self.group2.setGeometry(10,120,500,280)
     self.group2.show()
     self.group3 = QGroupBox(self.group2)
     self.group3.setObjectName('albuminfos')
     self.group3.setGeometry(10,15,200,245)
     self.group3.show()
     self.itemlist = QListWidget(self.group2)
     self.itemlist.setGeometry(250,15,230,245)
     self.itemlist.show()
     self.dlgroup = QGroupBox(parent)
     self.dlgroup.setObjectName('dlgroup')
     self.dlgroup.setGeometry(10,420,500,100)
     self.dlgroup.show()
     self.dlgroup.dlbutton = QPushButton('Download', self.dlgroup)
     self.dlgroup.dlbutton.setObjectName('dlbutton')
     self.dlgroup.dlbutton.move(10,20)
     self.dlgroup.dlbutton.show()
     self.dlgroup.progressbar = QProgressBar(self.dlgroup)
     self.dlgroup.progressbar.setObjectName('progressbar')
     self.dlgroup.progressbar.setGeometry(100,21,380,21)
     self.dlgroup.progressbar.show()
     self.dlgroup.dlinfos = QLabel(self.dlgroup)
     self.dlgroup.dlinfos.setGeometry(100,70,200,21)
     self.dlgroup.dlinfos.show()
     self.dlgroup.dledfile = QLabel(self.dlgroup)
     self.dlgroup.dledfile.setGeometry(300,70,200,21)
     self.dlgroup.dledfile.show()
     self.dlgroup.dlto = QLineEdit('C:\\', self.dlgroup)
     self.dlgroup.dlto.setGeometry(100,50,350,21)
     self.dlgroup.dlto.show()
     self.dlgroup.dlto.changebt = QToolButton(self.dlgroup)
     self.dlgroup.dlto.changebt.setObjectName('dltobt')
     self.dlgroup.dlto.changebt.setGeometry(10,50,75,21)
     self.dlgroup.dlto.changebt.setText('To')
     self.dlgroup.dlto.changebt.show()
     self.dlgroup.dlto.openf = QPushButton('Open', self.dlgroup)
     self.dlgroup.dlto.openf.setGeometry(455,50,35,21)
     self.dlgroup.dlto.openf.setObjectName('openfolder')
     self.dlgroup.dlto.openf.show()  
     self.album = QLabel(self.group3)
     self.artist = QLabel(self.group3)
     self.year = QLabel(self.group3)
     self.tracks = QLabel(self.group3)
     self.coverart = QLabel(self.group3)
     self.urlbar.setFocus(True)
     self.connect(self.parsebutton, SIGNAL('clicked()'), self.parseclicked )
     self.connect(self.dlgroup.dlbutton, SIGNAL('clicked()'), self.launchdl)
     self.connect(self.dlgroup.dlto.changebt, SIGNAL('clicked()'), self.changedir)
     self.connect(self.dlgroup.dlto.openf, SIGNAL('clicked()'), self.openfolder)
コード例 #47
0
ファイル: nPhoto.py プロジェクト: g3rg/nPhoto
class NPhotoMainWindow(QMainWindow):
    rootAlbum = None
    currentPage = 0
    
    def __init__(self, parent=None):
        super(NPhotoMainWindow, self).__init__(parent)

        self.image = None 
        self.status = self.statusBar()
        self.status.setSizeGripEnabled(False)

        fileMenu = self.menuBar().addMenu("&File")
        fileEditAction = createAction(self, "&Edit", self.doEdit, "Ctrl-E", "fileedit", "Edit photo details")
        fileDeleteAction = createAction(self, "&Delete", self.doDelete, "Ctrl-D", "filedelete", "Delete selected file(s)")
        fileImportAction = createAction(self, "&Import", self.doImport, "Ctrl-I", "fileimport", "Import photos into your library")
        fileRescanLibraryAction = createAction(self, "&Rescan", self.doRescan, "Ctrl-R", "filerescan", "Rescan library folder and update sidecar files, and thumbnails")
        fileBackupAction = createAction(self, "&Backup", self.doBackup, "Ctrl-B", "filebkup", "Backup your library")
        fileSettingsAction = createAction(self, "&Settings", self.doSettings, "Ctrl-S", "filesettings", "Settings")
        fileQuitAction = createAction(self, "&Quit", self.close, "Ctrl+Q", "filequit", "Close the application")

        helpMenu = self.menuBar().addMenu("&Help")
        helpAboutAction = createAction(self, "&About", self.doAbout, None, "helpabout", "About nPhoto")
        
        addActions(fileMenu, (fileEditAction, fileDeleteAction, None, fileImportAction, fileRescanLibraryAction,
                              fileBackupAction, fileSettingsAction, None, fileQuitAction))
        addActions(helpMenu, (helpAboutAction,))
    
        size = getSettingQVar("MainWindow/Size", QSize(600,500)).toSize()
        self.resize(size)
        position = getSettingQVar("MainWindow/Position", QPoint(0,0)).toPoint()
        self.move(position)
        self.restoreState(getSettingQVar("MainWindow/State").toByteArray())
        self.setWindowTitle("nPhoto")

        self.controlFrame = QFrame()
        self.controlLayout = QBoxLayout(QBoxLayout.TopToBottom)

        #TODO Make this a combo box that populates the tree by date or by folder
        self.viewByCombo = QLabel("PLACEHOLDER")
        
        self.tree = QTreeWidget()

        self.tree.setColumnCount(1)
        self.tree.setHeaderLabels(["Album"])
        self.tree.setItemsExpandable(True)

        self.connect(self.tree, SIGNAL("itemSelectionChanged()"), self.treeSelection)

        self.controlLayout.addWidget(self.viewByCombo)
        self.controlLayout.addWidget(self.tree)

        self.controlFrame.setLayout(self.controlLayout)

        self.browserFrame = QFrame()

        self.browserGrid = QGridLayout()

        self.imageLabels = []
        for row in range(0,BROWSER_GRID_HEIGHT):
            self.imageLabels.append([])
            for col in range(0,BROWSER_GRID_WIDTH):
                self.imageLabels[row].append(QLabel())
                self.imageLabels[row][col].setBackgroundRole(QPalette.Base)
                self.imageLabels[row][col].setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
                self.imageLabels[row][col].setScaledContents = True
                self.imageLabels[row][col].setAlignment(Qt.AlignCenter)
                self.imageLabels[row][col].setStyleSheet("border:2px solid #000")

                dbl = functools.partial(self.imgDoubleClick, row, col)
                click = functools.partial(self.imgMouseRelease, row, col)
                
                self.imageLabels[row][col].mouseDoubleClickEvent = dbl
                self.imageLabels[row][col].mouseReleaseEvent = click
                self.browserGrid.addWidget(self.imageLabels[row][col],row,col)

        self.prevPage = QPushButton("Prev")
        self.pageInfoLabel = QLabel("Page 0 of 0")
        self.pageInfoLabel.setAlignment(Qt.AlignCenter)
        self.nextPage = QPushButton("Next")

        self.prevPage.clicked.connect(self.goPreviousPage)
        self.nextPage.clicked.connect(self.goNextPage)
        
        self.browserGrid.addWidget(self.prevPage, row+1, 0)
        self.browserGrid.addWidget(self.pageInfoLabel, row+1, 1)
        self.browserGrid.addWidget(self.nextPage, row+1, 2)

        self.browserFrame.setLayout(self.browserGrid)

        self.mainSplitter = QSplitter(Qt.Horizontal)
        self.mainSplitter.addWidget(self.controlFrame)
        self.mainSplitter.addWidget(self.browserFrame)
        self.mainSplitter.setStretchFactor(1,4)
        
        self.setCentralWidget(self.mainSplitter)

        self.mainSplitter.restoreState(getSettingQVar("MainWindow/Splitter").toByteArray())

        if getSettingStr("Paths/Library") not in (None, ''):
            QTimer.singleShot(0, self.loadLibrary)
        else:
            self.status.showMessage("No Library Path in settings", 10000)

    def getPhotoByBrowserLocation(self, row, col):
        idx = ((self.currentPage - 1) * BROWSER_THUMBS_PER_PAGE) + (row * BROWSER_GRID_WIDTH) + col
        if idx < len(self.currentAlbum.photos):
            return self.currentAlbum.photos[idx]
        else:
            return None

    def imgDoubleClick(self, row, col, event):

        if event.button() == Qt.LeftButton:
            if event.modifiers() & Qt.ControlModifier or event.modifiers() & Qt.AltModifier \
                    or event.modifiers() & Qt.ShiftModifier:
                pass
            else:
                curr = self.getPhotoByBrowserLocation(row,col)
                if curr:
                    self.currentSelection = [curr,]
                    self.highlightSelected()
                    self.doEdit()        

    def imgMouseRelease(self, row, col, event):
        if event.button() == Qt.LeftButton:
            if event.modifiers() & Qt.ControlModifier or event.modifiers() & Qt.AltModifier \
                or event.modifiers() & Qt.ShiftModifier:
                pass
            else:
                curr = self.getPhotoByBrowserLocation(row,col)
                if curr:
                    if not hasattr(self, "currentSelection"):
                        self.currentSelection = []

                    if curr in self.currentSelection:
                        self.currentSelection.remove(curr)
                    else:
                        self.currentSelection.append(curr)

        self.highlightSelected()

    def highlightSelected(self):
        if hasattr(self, "currentSelection"):
            for x in range(0, BROWSER_GRID_HEIGHT):
                for y in range(0, BROWSER_GRID_WIDTH):
                    ph = self.getPhotoByBrowserLocation(x,y)
                    if ph:
                        if ph in self.currentSelection:
                            self.imageLabels[x][y].setStyleSheet("border:2px solid #FFF")
                        else:
                            self.imageLabels[x][y].setStyleSheet("border:2px solid #000")



    def regenAlbumThumbnails(self, album):
        for al in album.albums:
            self.regenAlbumThumbnails(al)

        for ph in album.photos:
            createThumbnail(ph.path, True)
        
    def doRescan(self):
        #TODO Rebuild sidecar files!

        self.regenAlbumThumbnails(self.rootAlbum)
        self.reloadLibrary()

        

    def treeSelection(self):
        curr = self.tree.currentItem()
        path = curr.data(0,0).toString()
        tmp = curr
        while tmp.parent() is not None:
            tmp = tmp.parent()
            path = tmp.data(0,0).toString() + "." + path

        album = self.getAlbum(path)
        if hasattr(self, 'currentAlbum'):
            if self.currentAlbum != album:
                self.currentAlbum = album
        else:
            self.currentAlbum = album
        self.changeAlbums()

    def changeAlbums(self):
        if len(self.currentAlbum.photos) == 0:
            self.currentPage = 0
        else:
            self.currentPage = 1
        
        for row in range(0, BROWSER_GRID_HEIGHT):
            for col in range(0, BROWSER_GRID_WIDTH):
                if len(self.currentAlbum.photos)<= (row*BROWSER_GRID_WIDTH + col):
                    self.imageLabels[row][col].setPixmap(QPixmap())
                else:
                    self.imageLabels[row][col].setPixmap(loadQPixMap(self.image, self.currentAlbum.photos[
                            (BROWSER_THUMBS_PER_PAGE * (self.currentPage - 1)) + row*BROWSER_GRID_WIDTH+col]
                                                                          .path, self.imageLabels[0][0].width(), self.imageLabels[0][0].height(), True))
                    self.imageLabels[row][col].adjustSize()

        self.updatePageInfo()

    def loadPageThumbs(self):
        for row in range(0, BROWSER_GRID_HEIGHT):
            for col in range(0, BROWSER_GRID_WIDTH):
                if len(self.currentAlbum.photos)<= (
                            (BROWSER_THUMBS_PER_PAGE * (self.currentPage - 1)) + row*BROWSER_GRID_WIDTH + col):
                    self.imageLabels[row][col].setPixmap(QPixmap())
                else:
                    self.imageLabels[row][col].setPixmap(loadQPixMap(self.image, self.currentAlbum.photos[
                            (BROWSER_THUMBS_PER_PAGE * (self.currentPage - 1)) + row*BROWSER_GRID_WIDTH+col]
                                                                          .path, self.imageLabels[0][0].width(), self.imageLabels[0][0].height(), True))
                    self.imageLabels[row][col].adjustSize()


    def goPreviousPage(self):
        if self.currentPage > 1:
            self.currentPage -= 1
            self.loadPageThumbs()
            self.updatePageInfo()

    def goNextPage(self):
        if self.currentPage < self.getMaxPage():
            self.currentPage += 1
            self.loadPageThumbs()
            self.updatePageInfo()

    def getMaxPage(self):
        totalPages = len(self.currentAlbum.photos) / BROWSER_THUMBS_PER_PAGE
        if (len(self.currentAlbum.photos) % BROWSER_THUMBS_PER_PAGE) != 0:
            totalPages += 1
        return totalPages
        

    def updatePageInfo(self):
        if self.currentPage == 0:
            self.pageInfoLabel.setText("Page 0 of 0")
        else:
            self.pageInfoLabel.setText("Page %d of %d" % (self.currentPage, self.getMaxPage()))
                                                   
    def getAlbum(self, path):
        nodes = path.split(".")
        if nodes[0] != 'Library':
            print "WTF?!?!?!"
        else:
            album = self.rootAlbum
            for albumName in nodes[1:]:
                album = album.albums[unicode(albumName)]

            return album
        
    def doBackup(self):
        libDir = getSettingStr("Paths/Library")
        bkupPaths = getSettingStr("Paths/Backup")
        
        if libDir in (None,  ''):
            QMessageBox.warning(self, "Backup Failed", "You need to specify a library directory in your settings")
            return
        if not os.path.exists(libDir) or os.path.isfile(libDir):
            QMessageBox.warning(self, "Backup Failed", "The library directory in your settings either doesn't exist, or its not a directory")
            return        
        
        if bkupPaths in (None,  ''):
            QMessageBox.warning(self, "Backup Failed",  "You need to specify at least one backup directory in your settings")
            return

        dt = datetime.date.today()
        bkupDirName = str(dt.year) + str(dt.month) + str(dt.day)

        for path in bkupPaths.split(","):
            if not os.path.exists(path.strip()) or os.path.isfile(path.strip()):
                QMessageBox.warning(self, "Backup Failed", "The backup directory <%s> in your settings either doesn't exist, or its not a directory" % (path))
                return
        
            if os.path.exists(path.strip() + os.sep + bkupDirName):
                QMessageBox.warning(self, "Backup Failed", "There is already a backup for today in a backup directory <%s>" % (path.strip()))
                return
        
        for path in bkupPaths.split(","):
            shutil.copytree(libDir, path.strip() + os.sep + bkupDirName)
        
        QMessageBox.information(self, "Backup", "Backup completed!")

    def doDelete(self):
        if hasattr(self, "currentSelection"):
            if len(self.currentSelection) > 0:
                msg = "Are you sure you want to delete the selected image?"
                if len(self.currentSelection) > 1:
                    msg = "Are you sure you want to delete the %s selected images?" % len(self.currentSelection)
                    
                if QMessageBox.warning(self, "Delete Image(s)", msg,
                                             QMessageBox.Yes|QMessageBox.No) == QMessageBox.Yes:
                    for ph in self.currentSelection:
                        msg = ph.delete()
                        if msg not in (None, ''):
                            QMessageBox.warning(self, "Error while deleting", msg)
                            break

                    self.reloadLibrary()
                    

    def reloadLibrary(self):
        self.currentSelection = []
        self.highlightSelected()
        
        currPage = self.currentPage

        self.loadLibrary()
        if currPage > self.getMaxPage():
            #Assumes you can't delete more than one page worth of photos at a time
            currPage = self.getMaxPage()

        self.currentPage = currPage
        self.loadPageThumbs()
        self.updatePageInfo()


    def doEdit(self):
        if hasattr(self, "currentSelection"):
            if len(self.currentSelection) == 1:
                ph = self.currentSelection[0]
                comment = ph.comment
                keywords = (" ".join(ph.keywords)).strip()
                dialog = EditPhotoDialog(self, ph.path, comment, keywords)
                if dialog.exec_():
                    ph.comment = unicode(dialog.commentEdit.text()).strip()
                    ph.keywords = unicode(dialog.keywordEdit.text()).strip().split(" ")
                    ph.save(ph.path)

    def doSettings(self):
        libPath = getSettingStr("Paths/Library", "")
        backupPaths = getSettingStr("Paths/Backup", "")
        fileExt = getSettingStr("FileExtensions", "jpg, CR2")
        fileExtOther = getSettingStr("FileExtensionsOther", "mov, avi")
        
        
        dialog = SettingsDialog(self, libPath, backupPaths, fileExt, fileExtOther)
        if dialog.exec_():
            saveSetting("Paths/Library", dialog.libPathEdit.text())
            saveSetting("Paths/Backup", dialog.backupPathsEdit.text())
            saveSetting("FileExtensions", dialog.fileExtensionEdit.text())
            saveSetting("FileExtensionsOther", dialog.fileExtensionOtherEdit.text())
            
            self.status.showMessage("Settings updated", 5000)
            

    def buildTree(self, parentNode, parentAlbum):
        for name in parentAlbum.albums:
            childNode = QTreeWidgetItem(parentNode, [name])
            childAlbum = parentAlbum.albums[name]
            if childAlbum.albums != None and len(childAlbum.albums) > 0:
                self.buildTree(childNode, childAlbum)

    def loadLibrary(self):
        self.status.showMessage("Loading Photo Library")

        self.rootAlbum = self.loadAlbum(getSettingStr("Paths/Library"), "Library")

        if self.rootAlbum == None:
            self.rootAlbum = Album(name="Library")

        self.refreshTree()
        
        self.status.showMessage("Library successfully loaded", 5000)

    def refreshTree(self):
        self.tree.clear()
        node = QTreeWidgetItem(self.tree, ["Library"])
        self.buildTree(node, self.rootAlbum)
        self.tree.setCurrentItem(node)

    def loadAlbum(self, path, title = None):
        album = Album()
        if title not in (None, ''):
            album.name = title
        else:
            album.name = path[path.rfind(os.sep)+1:]
            
        album.albums = {}
        album.photos = []
        album.path = path

        files = os.listdir(path)
        files.sort()

        tmpPhotos = []
        for fl in files:
            if not os.path.isfile(path + os.sep + fl):
                album.albums[fl] = self.loadAlbum(path + os.sep + fl)
            else:
                if self.isImageFile(path + os.sep + fl):
                    ph = None
                    if os.path.exists(path + os.sep + fl + ".sidecar"):
                        ph = Photo.load(path + os.sep + fl + ".sidecar")
                    else:
                        ph = Photo()
                        ph.comment = ""
                        ph.keywords = {}
                        ph.srcPath = None
                        ph.path = path + os.sep + fl
                        exif = loadExif(path + os.sep + fl, EXIF_TAGS)
                        ph.setExif(exif)
                        ph.save(path + os.sep + fl)

                    ph.path = path + os.sep + fl
                    tmpPhotos.append(ph)

        album.photos = sorted(tmpPhotos, key = lambda photo: photo.date)
        return album

    def doImport(self):
        libPath = getSettingStr("Paths/Library")
        fileExt = getSettingStr("FileExtensions")
        
        if libPath in (None,  ''):
            QMessageBox.warning(self, "Import Failed",  "You need to specify a library directory in your settings")
            return
        
        if not os.path.exists(libPath) or os.path.isfile(libPath):
            QMessageBox.warning(self, "Import Failed", "The library directory in your settings either doesn't exist, or its not a directory")
            return
            
        if not fileExt or fileExt in (None, ''):
            QMessageBox.warning(self, "Import Failed", "You need to specify file extensions to manage in your settings")
            return

        lastImport = getSettingStr("Paths/LastImport")

        importFrom = QFileDialog.getExistingDirectory(self, "Choose a Path to Import From", lastImport)
        
        if importFrom in (None,  ''):
            return
        
        if not os.path.exists(importFrom) or os.path.isfile(importFrom):
            QMessageBox.warning(self, "Import Failed", "The import directory either doesn't exist, or is not a directory")
            return

        if importFrom == libPath:
            QMessageBox.warning(self, "Import Failed", "Your import directory and library directory can not be the same")
            return

        imd = ImportMetadataDialog(self)

        if imd.exec_():
            album = imd.albumEdit.text()
            comments = imd.commentsEdit.text()
            keywords = imd.keywordsEdit.text()
            
            if album and album not in (None, ''):
                albumpath = album + os.sep
            else:
                album = None
                albumpath = ""
            
            if not keywords or keywords in (None, ''):
                keywords = ""

            if not comments or comments in (None, ''):
                comments = ""

            paths = self.buildFileList(importFrom)
            numTotal = len(paths)
            
            nonDupes = self.removeDuplicates(paths, importFrom, albumpath)
            numDuplicates = numTotal - len(nonDupes)
            
            if QMessageBox.question(self, "Import", "Out of %d files found, %d look to be duplicates. Continue with import?"
                                    % (numTotal,  numDuplicates), QMessageBox.Yes|QMessageBox.No) == QMessageBox.Yes:
                
                saveSetting("Paths/LastImport", importFrom)
                
                for path in nonDupes:
                    dest = self.buildLibPath(importFrom, path, albumpath)
                    copyFileIncludingDirectories(path, dest)
                    # TODO Handle copy failure exceptions!
                    
                    if not os.path.exists(dest):
                        QMessageBox.warming(self, "Import Failed", "The file <%s> was not imported properly, aborting import" % (path))
                        return
                    if self.isImageFile(path):
                        exif = loadExif(unicode(path), EXIF_TAGS)
                        ph = Photo()
                        ph.path = dest
                        ph.srcPath = path
                        ph.comment = comments
                        ph.keywords = keywords
                        ph.setExif(exif)
                        ph.save(dest)

                        #Create Thumbnail
                        createThumbnail(unicode(ph.path))
                        
                QMessageBox.information(self, "Import", "Import completed")

                self.loadLibrary()
            
    def buildLibPath(self, importFrom, path, albumpath):
        relPath = path[len(importFrom):]
        libPath = getSettingStr("Paths/Library") + os.sep + albumpath + relPath
        
        return libPath

        
    def isImageFile(self, filepath):
        extensionList = unicode(getSettingStr("FileExtensions")).split(",")
        for extension in extensionList:
            if unicode(filepath).upper().endswith(unicode(extension).upper()):
                return True
        return False

    def isOtherManagedFile(self, filepath):
        #TODO Implement list of other files to import into lib folders and to backup
        extensionList = unicode(getSettingStr("FileExtensionsOther")).split(",")
        for extension in extensionList:
            if unicode(filepath).upper().endswith(unicode(extension).upper()):
                return True
        return False
    

        
    def removeDuplicates(self, paths, importFrom, albumpath):
        nonDupes = []
        
        for path in paths:
            libPath = self.buildLibPath(importFrom, path, albumpath)
            if not os.path.exists(libPath):
                nonDupes.append(path)
        
        return nonDupes

    def buildFileList(self, importFrom):
        #TODO Can probably be done with Glob or whatever it is?
        paths = []
        for f in os.listdir(importFrom):
            fullpath = importFrom + os.sep + f
            
            if not os.path.isfile(fullpath):
                paths.extend(self.buildFileList(fullpath))
            else:
                if self.isImageFile(fullpath):
                    paths.append(fullpath)
                elif self.isOtherManagedFile(fullpath):
                    paths.append(fullpath)
                    
        return paths

    def closeEvent(self, event):
        saveSetting("MainWindow/Size", self.size())
        saveSetting("MainWindow/Position", self.pos())
        saveSetting("MainWindow/State", self.saveState())
        saveSetting("MainWindow/Splitter", self.mainSplitter.saveState())

    def doAbout(self):
        QMessageBox.about(self, "About nPhoto",
                "<p>nPhoto allows simple reviewing, commenting, and keywording of images, useful for running"
                                " on a netbook while travelling, to then import into programs such as Lightroom"
                                " on return from your holiday</p>")
コード例 #48
0
    def __init__(
            self,
            ressource_directory,
            validation_callback: callable,
            exit_callback: callable,
            play_callback: callable,
            screen_id=-1,
            nb_player=1,
            nb_life=3,
            timer_proportions=(0.14, 0.25),
            life_proportions=(0.12, 0.75),
            player_proportions=(1, 0.7),
            player_spacing_proportion=0.33,
            border_proportion=0.03,
            multi_life_spacing_proportion=0.12,
            alpha_color="FF00FF",
            validate_keys=(65, 32, 16777220,
                           43),  # keys : 'a', space, enter, '+'
            dev_mode=False):

        if dev_mode:  # TODO utiliser logger
            print(" Initalisation TwistCanWindow (en mode développeur)")
        # ----- Init de la fenêtre -----
        self.main_app = QApplication(sys.argv)
        self.main_app.setOverrideCursor(Qt.BlankCursor)

        # ----- Analyse des paramètres du constructeur -----
        # Ajouter le '#' dans les html color
        if type(alpha_color) == str and len(alpha_color) == 6:
            alpha_color = "#" + alpha_color

        self.validate_keys = validate_keys
        self.validation_callback = validation_callback
        self.play_callback = play_callback

        self.exit_callback = exit_callback

        # récupérer les dimension de l'écran selectioné
        if screen_id < 0:
            screen_id = QDesktopWidget().screenCount()
        screen_size = QDesktopWidget().screenGeometry(screen_id).size()
        border_size = screen_size.width() * border_proportion
        timer_size = QSize(
            round((screen_size.width() - border_size * 2) *
                  timer_proportions[0]),
            round((screen_size.height() - border_size * 2) *
                  timer_proportions[1]))
        player_size = QSize(
            round(screen_size.width() * player_proportions[0]),
            round(screen_size.height() * player_proportions[1]))
        life_size = QSize(
            round(
                (screen_size.width() - border_size * 2) * life_proportions[0]),
            round((screen_size.height() - border_size * 2) *
                  life_proportions[1]))

        # ----- Construction de l'interface -----
        # Pose widget
        if dev_mode:
            print("  Initialisation Background")
        self.pose_widget = PoseWidget(
            ressource_directory,
            screen_size,
            player_size,
            player_spacing_proportion,
            alpha_color=alpha_color,
            key_press_event_callback=self.keyPressEventCallback,
            dev_mode=dev_mode)
        self.pose_widget.setWindowTitle("TwistCam")
        # self.setWindowIcon(QtGui.QIcon('web.png'))
        print("Déplacement du jeu sur l'écran le plus a droite [==>]")
        # TODO impove avec l'id du screen
        self.pose_widget.move(QDesktopWidget().width() - 1, 0)
        self.pose_widget.showFullScreen()
        # Pose Layout
        main_layout = QVBoxLayout()
        main_layout.setSpacing(0)
        main_layout.setContentsMargins(border_size, border_size, border_size,
                                       border_size)
        self.pose_widget.setLayout(main_layout)
        # Timer
        push_right_layout = QBoxLayout(QBoxLayout.RightToLeft)
        main_layout.addLayout(push_right_layout)
        self.timer = TimerWidget(
            ressource_directory, timer_size, dev_mode=dev_mode
        )  # TODO setup clock_dim and clock_color from config
        push_right_layout.addWidget(self.timer)
        push_right_layout.setSpacing(0)
        push_right_layout.addSpacing(screen_size.width() - 2 * border_size -
                                     timer_size.width())
        # Lifes
        if nb_player == 1:
            # setup special pour 1 seul joueur
            push_right_layout_2 = QBoxLayout(QBoxLayout.RightToLeft)
            push_right_layout_2.setSpacing(0)
            main_layout.addLayout(push_right_layout_2)
            self.lifes = [
                LifeWidget(ressource_directory,
                           life_size,
                           nb_life,
                           dev_mode=dev_mode)
            ]
            push_right_layout_2.addWidget(self.lifes[0])
            push_right_layout_2.addSpacing(screen_size.width() -
                                           2 * border_size -
                                           life_size.width() -
                                           (timer_size.width() -
                                            life_size.width()))
        else:
            multi_life_layout = QHBoxLayout()
            life_size.setWidth(self.pose_widget.player_pixel_spacing *
                               nb_player)
            life_offset = (screen_size.width() - 2 * border_size -
                           life_size.width()) * 0.5
            multi_life_layout.setContentsMargins(life_offset, 0, life_offset,
                                                 0)
            multi_life_layout.setSpacing(
                self.pose_widget.player_pixel_spacing *
                multi_life_spacing_proportion)
            self.lifes = [
                LifeWidget(ressource_directory,
                           QSize(
                               self.pose_widget.player_pixel_spacing *
                               (1 - multi_life_spacing_proportion),
                               life_size.height()),
                           nb_life,
                           dev_mode=dev_mode) for k in range(nb_player)
            ]
            for life in self.lifes:
                multi_life_layout.addWidget(life)
            main_layout.addSpacing(screen_size.height() - 2 * border_size -
                                   timer_size.height() - life_size.height())
            main_layout.addLayout(multi_life_layout)
        # ----- Signaux -----
        self.s = self.Signaux(self)
コード例 #49
0
ファイル: nPhoto.py プロジェクト: g3rg/nPhoto
    def __init__(self, parent=None):
        super(NPhotoMainWindow, self).__init__(parent)

        self.image = None 
        self.status = self.statusBar()
        self.status.setSizeGripEnabled(False)

        fileMenu = self.menuBar().addMenu("&File")
        fileEditAction = createAction(self, "&Edit", self.doEdit, "Ctrl-E", "fileedit", "Edit photo details")
        fileDeleteAction = createAction(self, "&Delete", self.doDelete, "Ctrl-D", "filedelete", "Delete selected file(s)")
        fileImportAction = createAction(self, "&Import", self.doImport, "Ctrl-I", "fileimport", "Import photos into your library")
        fileRescanLibraryAction = createAction(self, "&Rescan", self.doRescan, "Ctrl-R", "filerescan", "Rescan library folder and update sidecar files, and thumbnails")
        fileBackupAction = createAction(self, "&Backup", self.doBackup, "Ctrl-B", "filebkup", "Backup your library")
        fileSettingsAction = createAction(self, "&Settings", self.doSettings, "Ctrl-S", "filesettings", "Settings")
        fileQuitAction = createAction(self, "&Quit", self.close, "Ctrl+Q", "filequit", "Close the application")

        helpMenu = self.menuBar().addMenu("&Help")
        helpAboutAction = createAction(self, "&About", self.doAbout, None, "helpabout", "About nPhoto")
        
        addActions(fileMenu, (fileEditAction, fileDeleteAction, None, fileImportAction, fileRescanLibraryAction,
                              fileBackupAction, fileSettingsAction, None, fileQuitAction))
        addActions(helpMenu, (helpAboutAction,))
    
        size = getSettingQVar("MainWindow/Size", QSize(600,500)).toSize()
        self.resize(size)
        position = getSettingQVar("MainWindow/Position", QPoint(0,0)).toPoint()
        self.move(position)
        self.restoreState(getSettingQVar("MainWindow/State").toByteArray())
        self.setWindowTitle("nPhoto")

        self.controlFrame = QFrame()
        self.controlLayout = QBoxLayout(QBoxLayout.TopToBottom)

        #TODO Make this a combo box that populates the tree by date or by folder
        self.viewByCombo = QLabel("PLACEHOLDER")
        
        self.tree = QTreeWidget()

        self.tree.setColumnCount(1)
        self.tree.setHeaderLabels(["Album"])
        self.tree.setItemsExpandable(True)

        self.connect(self.tree, SIGNAL("itemSelectionChanged()"), self.treeSelection)

        self.controlLayout.addWidget(self.viewByCombo)
        self.controlLayout.addWidget(self.tree)

        self.controlFrame.setLayout(self.controlLayout)

        self.browserFrame = QFrame()

        self.browserGrid = QGridLayout()

        self.imageLabels = []
        for row in range(0,BROWSER_GRID_HEIGHT):
            self.imageLabels.append([])
            for col in range(0,BROWSER_GRID_WIDTH):
                self.imageLabels[row].append(QLabel())
                self.imageLabels[row][col].setBackgroundRole(QPalette.Base)
                self.imageLabels[row][col].setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
                self.imageLabels[row][col].setScaledContents = True
                self.imageLabels[row][col].setAlignment(Qt.AlignCenter)
                self.imageLabels[row][col].setStyleSheet("border:2px solid #000")

                dbl = functools.partial(self.imgDoubleClick, row, col)
                click = functools.partial(self.imgMouseRelease, row, col)
                
                self.imageLabels[row][col].mouseDoubleClickEvent = dbl
                self.imageLabels[row][col].mouseReleaseEvent = click
                self.browserGrid.addWidget(self.imageLabels[row][col],row,col)

        self.prevPage = QPushButton("Prev")
        self.pageInfoLabel = QLabel("Page 0 of 0")
        self.pageInfoLabel.setAlignment(Qt.AlignCenter)
        self.nextPage = QPushButton("Next")

        self.prevPage.clicked.connect(self.goPreviousPage)
        self.nextPage.clicked.connect(self.goNextPage)
        
        self.browserGrid.addWidget(self.prevPage, row+1, 0)
        self.browserGrid.addWidget(self.pageInfoLabel, row+1, 1)
        self.browserGrid.addWidget(self.nextPage, row+1, 2)

        self.browserFrame.setLayout(self.browserGrid)

        self.mainSplitter = QSplitter(Qt.Horizontal)
        self.mainSplitter.addWidget(self.controlFrame)
        self.mainSplitter.addWidget(self.browserFrame)
        self.mainSplitter.setStretchFactor(1,4)
        
        self.setCentralWidget(self.mainSplitter)

        self.mainSplitter.restoreState(getSettingQVar("MainWindow/Splitter").toByteArray())

        if getSettingStr("Paths/Library") not in (None, ''):
            QTimer.singleShot(0, self.loadLibrary)
        else:
            self.status.showMessage("No Library Path in settings", 10000)
コード例 #50
0
ファイル: TabDownloads.py プロジェクト: MaximeCheramy/pyrex
class TabDownloads(QWidget):
    instance = None

    def __init__(self, search, parent=None):
        QWidget.__init__(self, parent)
        # Load de l'UI
        PyQt4.uic.loadUi('ui/downloads.ui', self)
        # Ajout de la progressBar
        self.progressBar = QProgressBar()
        self.progressBar.setMinimum(0)
        self.progressBar.setMaximum(100)
        self.progressBar.hide()
        self.HLayout = QBoxLayout(QBoxLayout.LeftToRight)
        self.HLayout.addWidget(self.progress_label)
        self.HLayout.addWidget(self.progressBar)
        self.formLayout_3.addRow(self.HLayout)
        # Vars 
        TabDownloads.instance = self
        self.downloads        = Downloads()
        self.pos              = None
        self.download_looked  = None
        # Affichage custom
        #self.downloads_table.setStyleSheet(\
        #        "QTableView::item{ \
        #         border-right-style:solid; \
        #         border-width:0.5; \
        #         border-color: #9B9B9B; \
        #         }")
        # On autorise la creation de menu contextuel
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        # Signaux
        self.customContextMenuRequested.connect(self.contextMenu)
        self.downloads_table.itemClicked.connect(self.show_info_download)
        # Init
        self.load_downloads()
        # On remove les finis et en erreur si Config.clean_dl_list = 1
        if Configuration.clean_dl_list == 1:
            self.clean_list_Action()
        #########################################################
        # On désactive les boutons qui sont pas encore implantés
        self.button_stop_all.setEnabled(False)        
        self.button_resume_all.setEnabled(False)
        #########################################################

    def load_downloads(self):
        import xml.sax
        parser = xml.sax.make_parser()
        parser.setContentHandler(AnalyseDownloads(self.add_downloads))
        try:
            for line in open(os.path.expanduser("~") + '/.pyrex/downloads.xml'):
                parser.feed(line)
            self.downloads.save()
        except:
            pass

    def add_download(self, download):
        # Avant de filtrer on écrit le download
        #self.downloads.append(download) #TODO : pour quand on pourra resume, décommenter la ligne et ramener le save ici
                
        if download.state == 4 or download.progress == 0:
            rows = self.downloads_table.rowCount()
            self.downloads_table.insertRow(rows)
            self.downloads_table.setItem(rows, 0, MyQTableWidgetItem(download.file_share.name, download))
            self.downloads_table.setItem(rows, 1, QTableWidgetItem(download.get_progress()))
            self.downloads_table.setItem(rows, 2, QTableWidgetItem(download.state_str))
            self.downloads_table.setItem(rows, 3, QTableWidgetItem("0 ko/s"))
            self.downloads_table.setItem(rows, 5, QTableWidgetItem(download.date.strftime('%d/%m/%y')))
            self.downloads.append(download)
                    
        # TODO : à modifier probablement quand on aura le resume pour les downloads
        if download.state != 4 and download.progress == 0:
            # Signaux
            download.progressModified.connect(self.update_progress)
            download.stateChanged.connect(self.update_state)
            download.downloadFinished.connect(self.download_finished)
            download.speedModified.connect(self.update_speed)
        
        # On save
        self.downloads.save()
        
    def add_downloads(self, downloads):
        for download in downloads:
          self.add_download(download)
        
    def update_progress(self, download):
        item = self.downloads_table.findItems(download.file_share.name, Qt.MatchExactly)[0]
        row = self.downloads_table.row(item)
        self.downloads_table.item(row, 1).setText(download.get_progress())
        # On update la barre de progression si on est en train de regarder un download
        if self.download_looked == download:
            self.progressBar.setValue(int(download.progress))

    def update_speed(self, download):
        item = self.downloads_table.findItems(download.file_share.name, Qt.MatchExactly)[0]
        row = self.downloads_table.row(item)
        self.downloads_table.item(row, 3).setText(convert_speed_str(download.speed))
        
    def update_state(self, download):
        item = self.downloads_table.findItems(download.file_share.name, Qt.MatchExactly)[0]
        row = self.downloads_table.row(item)
        self.downloads_table.item(row, 2).setText(download.state_str)
        # On save
        self.downloads.save()
        
    def download_finished(self, download):
        if download.read_bytes == download.file_share.size:
            item = self.downloads_table.findItems(download.file_share.name, Qt.MatchExactly)[0]
            row = self.downloads_table.row(item)
            self.downloads_table.item(row, 2).setText("Finished!")
            self.downloads_table.item(row, 3).setText("")
            # On save
            self.downloads.save()
        else:
            print "Erreur dans le téléchargement"
            item = self.downloads_table.findItems(download.file_share.name, Qt.MatchExactly)[0]
            row = self.downloads_table.row(item)
            self.downloads_table.item(row, 2).setText("Error : invalid size :(")
            self.downloads_table.item(row, 3).setText("")
            # On save
            self.downloads.save()
            
    def contextMenu(self, pos):
        self.pos = pos
        menu = QMenu()
        # Actions 
        forceAction         = menu.addAction("Forcer la reprise")
        continueAction      = menu.addAction("Reprise")
        pauseAction         = menu.addAction("Pause")
        openAction          = menu.addAction("Ouvrir")
        abortAction         = menu.addAction("Annuler")
        supprListeAction    = menu.addAction("Supprimer de la liste")
        supprDiskAction     = menu.addAction("Supprimer de la liste et du disque")
        copyAction          = menu.addAction("Copier l'URL")
        searchAction        = menu.addAction("Rechercher des fichiers similaires")
        # On désactive les actions s'il n'y a pas de downloads
        if self.downloads == [] or self.downloads_table.currentRow() < 0:
            forceAction.setEnabled(False)
            continueAction.setEnabled(False)
            pauseAction.setEnabled(False)
            openAction.setEnabled(False)
            abortAction.setEnabled(False)
            supprListeAction.setEnabled(False)
            supprDiskAction.setEnabled(False)
            copyAction.setEnabled(False)
            searchAction.setEnabled(False)
        #########################################################
        # On désactive les boutons qui sont pas encore implantés
        forceAction.setEnabled(False)
        #continueAction.setEnabled(False)
        #pauseAction.setEnabled(False)        
        searchAction.setEnabled(False)        
        #########################################################
        # Signaux
        self.connect(forceAction, SIGNAL('triggered()'), self.force_Action)
        self.connect(continueAction, SIGNAL('triggered()'), self.continue_Action)
        self.connect(pauseAction, SIGNAL('triggered()'), self.pause_Action)
        self.connect(openAction, SIGNAL('triggered()'), self.open_Action)
        self.connect(abortAction, SIGNAL('triggered()'), self.abort_Action)
        self.connect(supprListeAction, SIGNAL('triggered()'), self.suppr_liste_Action)
        self.connect(supprDiskAction, SIGNAL('triggered()'), self.suppr_disk_Action)
        self.connect(copyAction, SIGNAL('triggered()'), self.copy_Action)
        self.connect(searchAction, SIGNAL('triggered()'), self.search_Action)
        # On affiche le menu
        menu.exec_(self.mapToGlobal(pos))
      
    def getDownloads(self):
        rows = self.downloads_table.selectionModel().selectedRows()
        return [self.downloads_table.item(row.row(), 0).download for row in rows]
          
    def force_Action(self):
        print "TODO"
        
    def continue_Action(self):
        for download in self.getDownloads():
            print "Resuming download"
            download.resume()
        self.display_resume_pause()
        
    def pause_Action(self):
        for download in self.getDownloads():
            print "Pausing download"
            download.pause()
        self.display_resume_pause()
        
    def open_Action(self):
        for download in self.getDownloads():
            open_file(download.local_path)
        
    def abort_Action(self):
        for download in self.getDownloads():
            download.stop()
        row = self.downloads_table.currentRow()
        self.downloads_table.item(row, 2).setText(u"Annulé!")
        self.downloads_table.item(row, 3).setText("")
  
    def remove_download(self, download, erase):
        download.stop()
        row = self.downloads_table.currentRow()
        # On supprime la ligne
        self.downloads_table.removeRow(row)
        # On supprime de la liste
        self.downloads.remove(download)    
        # On save
        self.downloads.save()
        if erase:
            try:
                os.remove(download.local_path)
            except OSError:
                try:
                    shutil.rmtree(download.local_path)
                except:
                    print "Erreur dans la suppression du fichier"

    def suppr_liste_Action(self):
        for download in self.getDownload():
            self.remove_download(download, False)
        
    def suppr_disk_Action(self):
        for download in self.getDownloads():
            self.remove_download(download, True)
        
    def copy_Action(self):
        pressPaper = QApplication.clipboard()
        text = '\n'.join([dl.local_path for dl in self.getDownloads()])
        pressPaper.setText(text)
        
    def search_Action(self):
        print "TODO"
        
    def show_info_download(self):
        download = self.getDownloads()[0]
        self.name_label.setText(u"Nom : {}".format(download.file_share.name))
        self.path_label.setText(u"Chemin local : {}".format(download.local_path))
        self.url_label.setText(u"URL : {}".format(download.file_share.url))
        self.size_label.setText(u"Taille : {}".format(download.file_share.str_size))   
        self.progressBar.show()     
        self.progressBar.setValue(int(download.progress))
        self.download_looked = download
        
    def clean_list_Action(self):
        remove_list = []
        for download in self.downloads:
            if download.state == 4 or download.state == 7:
                # On trouve la ligne
                item = self.downloads_table.findItems(download.file_share.name, Qt.MatchExactly)[0]
                row = self.downloads_table.row(item)
                # On la supprime
                self.downloads_table.removeRow(row)
                # On save pour après la boucle for
                remove_list.append(download)
        # On supprime de la liste
        for download in remove_list:
            self.downloads.remove(download)    
        # On save
        self.downloads.save()
                               
    def double_clicked(self, row, col):
        download = self.getDownloads()[0]
        if download:
            open_file(download.local_path)
            
    def display_resume_pause(self):
        downloads = self.getDownloads()
        pause = False
        resume = False
        if downloads:
            for download in downloads:
                if download.state == 5:
                    pause = True
                else:
                    resume = True
            self.button_pause.setEnabled(resume)
            self.button_resume.setEnabled(pause)
                    
    def clicked(self, row, col):
        self.display_resume_pause()    
        
    def resizeEvent(self, event):
        maxSize = self.downloads_table.size().width()
        # Nom Ficher : 24%
        self.downloads_table.horizontalHeader().resizeSection(0, maxSize*.24)
        # Avancement : 22%
        self.downloads_table.horizontalHeader().resizeSection(1, maxSize*.22)
        # Etat : 17%
        self.downloads_table.horizontalHeader().resizeSection(2, maxSize*.17)
        # Vitesse : 13% 
        self.downloads_table.horizontalHeader().resizeSection(3, maxSize*.13)
        # Fin : 12%
        self.downloads_table.horizontalHeader().resizeSection(4, maxSize*.12)
        event.accept()
コード例 #51
0
ファイル: gui.py プロジェクト: philipstahl/emotutor
    def init_ui(self):
        """ Creates the layout of the settings screen.
            Basic button functionality is designed here. Parameter settings
            have to be overwritten in init_parameters
        """
        button_layout = QBoxLayout(0)
        button_layout.addWidget(self.button("&Reset", self.reset))
        button_layout.addWidget(self.button("&Cancel", self.cancel))
        button_layout.addWidget(self.button("&Save", self.save))

        buttons = QWidget()
        buttons.setLayout(button_layout)

        main_layout = QBoxLayout(2)
        main_layout.addWidget(self.init_parameters())
        main_layout.addWidget(buttons)
        return main_layout