Ejemplo n.º 1
0
def grabWidget(widget, fileName, period=None):
    """Grabs the given widget into the given image filename. If period is
    None (default) it grabs immediately once and returns.
    If period is given and >0 means grab the image every period (in seconds).

    .. warning::
        this method **MUST** be called from the same thread which created
        the widget

    :param widget: the Qt widget to be grabbed
    :type widget: QtWidget
    :param fileName:  the name of the image file
    :type fileName: str
    :param period: period (seconds)
    :type period: float
    """
    if period is None:
        widgetName = widget.objectName()
        widgetTitle = widget.windowTitle()
        log.debug("Grabbing widget '%s' to '%s':", widgetName, fileName)
        try:
            pixmap = QtGui.QPixmap.grabWidget(widget)
            if fileName.endswith('.svg'):
                import qarbon.external.qt.QtSvg
                generator = qarbon.external.qt.QtSvg.QSvgGenerator()
                generator.setFileName(fileName)
                generator.setSize(pixmap.size())
                if hasattr(generator, 'setViewBox'):
                    viewBox = QtCore.QRect(QtCore.QPoint(0, 0), pixmap.size())
                    generator.setViewBox(viewBox)
                title = "Qarbon widget"
                if widgetTitle:
                    title += " - " + widgetTitle
                elif widgetName:
                    title += " - " + widgetName
                desc = "An SVG created by the qarbon widget grabber"
                generator.setTitle(title)
                generator.setDescription(desc)
                painter = QtGui.QPainter()
                painter.begin(generator)
                try:
                    painter.drawPixmap(0, 0, -1, -1, pixmap)
                finally:
                    painter.end()
            else:
                pixmap.save(fileName, quality=100)
        except Exception:
            log.warning("Could not save file into '%s':", fileName)
            log.debug("Details:", exc_info=1)

    ret = __GrabberThread(widget, fileName, period)
    ret.start()
    return ret
Ejemplo n.º 2
0
def getAction(text,
              parent=None,
              shortcut=None,
              icon=None,
              tooltip=None,
              toggled=None,
              triggered=None,
              data=None,
              context=QtCore.Qt.WindowShortcut):
    """Create a new QAction.

    This is function as the same effect as :func:`Action`. Please use
    :func:`Action` instead.

    :param text: label for the action
    :type text: str
    :param parent: parent QObject
    :type parent: QObject
    :param shortcut: optional shortcut
    :type shortcut: QtGui.QKeySequence
    :param icon: optional icon. Can be a QIcon or a string
    :type icon: QIcon or str
    :param tooltip: optional tool tip
    :type tooltip: str
    :param toggled: optional toggled slot
    :type toggled: callable
    :param data: optional data
    :type data: object
    :param context: action context
    :type context: ShortcutContext

    :return: a customized QAction
    :rtype: QAction
    """
    action = QtGui.QAction(text, parent)
    if triggered is not None:
        action.triggered.connect(triggered)
    if toggled is not None:
        action.toggled.connect(toggled)
        action.setCheckable(True)
    action.setIcon(Icon(icon))
    if shortcut is not None:
        action.setShortcut(shortcut)
    if tooltip is not None:
        action.setToolTip(tooltip)
        action.setStatusTip(tooltip)
    if data is not None:
        action.setData(data)
    #TODO: Hard-code all shortcuts and choose context=Qt.WidgetShortcut
    # (this will avoid calling shortcuts from another dockwidget
    #  since the context thing doesn't work quite well with these widgets)
    action.setShortcutContext(context)
    return action
Ejemplo n.º 3
0
    def __init__(self, view=None, parent=None, designMode=False):
        BaseToolBar.__init__(self,
                             name="Filter toolbar",
                             view=view,
                             parent=parent,
                             designMode=designMode)
        filterLineEdit = self._filterLineEdit = QtGui.QLineEdit(self)
        filterLineEdit.setSizePolicy(
            QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred,
                              QtGui.QSizePolicy.Preferred))
        filterLineEdit.setToolTip("Quick filter")
        filterLineEdit.textChanged.connect(self.onFilterChanged)
        filterLineEdit.textEdited.connect(self.onFilterEdited)
        self.addWidget(filterLineEdit)

        self._clearFilterAction = Action("Clear",
                                         parent=self,
                                         icon=getIcon("edit-clear"),
                                         tooltip="Clears the filter",
                                         triggered=self.onClearFilter)
        self.addAction(self._clearFilterAction)
Ejemplo n.º 4
0
 def create_integer_panel(self, input_data):
     panel = self._create_simple_panel(input_data)
     minimum = input_data.get('minimum', -sys.maxint)
     maximum = input_data.get('maximum', sys.maxint)
     step = input_data.get('step', 1)
     layout = panel.layout()
     self._ui.inputWidget = spinbox = QtGui.QSpinBox()
     spinbox.setMinimum(minimum)
     spinbox.setMaximum(maximum)
     spinbox.setSingleStep(step)
     if 'default_value' in input_data:
         spinbox.setValue(input_data['default_value'])
     layout.addWidget(spinbox, 0, 1)
     return panel, self._get_integer_value
Ejemplo n.º 5
0
    def __init__(self, parent=None, qobject=None):
        super(ObjectInfoWidget, self).__init__(parent)
        self.setWindowIcon(Icon("applications-development"))
        self.setWindowTitle("QObject Inspector")
        layout = QtGui.QHBoxLayout()
        self.setLayout(layout)
        layout.setSpacing(0)
        layout.setMargin(0)
        self.__splitter = splitter = QtGui.QSplitter(QtCore.Qt.Horizontal,
                                                     self)
        layout.addWidget(splitter)

        self.__form = form = PropertyEditor(parent=splitter, qobject=qobject)
        self.__tree = tree = TreeQObjectWidget(parent=splitter,
                                               qobject=qobject)
        splitter.addWidget(tree)
        splitter.addWidget(form)

        treeSelectionModel = tree.viewWidget().selectionModel()
        QtCore.QObject.connect(
            treeSelectionModel,
            QtCore.SIGNAL("selectionChanged(QItemSelection, QItemSelection)"),
            self.__onSelectionChanged)
Ejemplo n.º 6
0
    def __buildAxisGUI(self, axis):
        row = axis.index
        layout = self.content().layout()

        # create widgets
        label_widget = DisplayLabel(axis)
        position_widget = ValueSpinBox(axis)
        icon_widget = QtGui.QLabel()
        steps_widget = StepSize(axis)
        step_left_widget = StepLeftButton(axis)
        step_right_widget = StepRightButton(axis)
        stop_widget = StopButton(axis)

        # add widgets to container
        layout.addWidget(label_widget, row, Column.Label.value)
        layout.addWidget(position_widget, row, Column.Position.value)
        layout.addWidget(icon_widget, row, Column.Icon.value)
        layout.addWidget(steps_widget, row, Column.Steps.value)
        layout.addWidget(step_left_widget, row, Column.StepLeft.value)
        layout.addWidget(step_right_widget, row, Column.StepRight.value)
        layout.addWidget(stop_widget, row, Column.Stop.value)

        # initialize values
        label_widget.setValue(axis.label)

        position_widget.setValue(axis.position)
        position_widget.setState(axis.state)
        position_widget.setRange(*axis.limits)
        position_widget.setSingleStep(axis.currentStep)
        position_widget.setUnit(axis.unit)

        steps_widget.setSteps(axis.steps)
        steps_widget.setCurrentStep(axis.currentStep)

        # set buddy
        label_widget.setBuddy(position_widget)

        icon_widget.hide()

        # connect signals
        steps_widget.activated.connect(self.onUserCurrentStepsChanged)
        position_widget.valueApplied.connect(self.onUserPositionApplied)
        position_widget.valueChanged.connect(self.onUserPositionChanged)
        step_left_widget.clicked.connect(self.onUserStepLeft)
        step_right_widget.clicked.connect(self.onUserStepRight)
        stop_widget.clicked.connect(self.onUserStop)

        # initialize enable/disable and tooltips
        self.__updateAxis(axis)
Ejemplo n.º 7
0
 def _create_combobox_panel(self, input_data):
     panel = self._create_simple_panel(input_data)
     layout = panel.layout()
     self._ui.inputWidget = combobox = QtGui.QComboBox()
     items = input_data['data_type']
     for item in items:
         is_seq = not isinstance(item, (str, unicode)) and \
                  isinstance(item, collections.Sequence)
         if is_seq:
             text, userData = item
         else:
             text, userData = str(item), item
         combobox.addItem(text, userData)
     layout.addWidget(combobox, 0, 1)
     return panel, self._get_combobox_value
Ejemplo n.º 8
0
 def __init__(self,
              err_type=None,
              err_value=None,
              err_traceback=None,
              parent=None):
     QtGui.QDialog.__init__(self, parent)
     layout = QtGui.QVBoxLayout()
     self.setLayout(layout)
     if err_type is None and err_value is None and err_traceback is None:
         err_type, err_value, err_traceback = sys.exc_info()[:3]
     self._panel = ErrorWidget(err_type, err_value, err_traceback, self)
     self.setWindowTitle(self._panel.windowTitle())
     layout.setContentsMargins(0, 0, 0, 0)
     layout.setSpacing(0)
     layout.addWidget(self._panel)
     self._panel.buttonBox.accepted.connect(self.accept)
     self._panel.toggledDetails.connect(self._onShowDetails)
Ejemplo n.º 9
0
def Application(argv=None, **properties):
    """Returns a QApplication.

    If the process has initialized before a QApplication it returns the
    existing instance, otherwise it creates a new one.

    When a QApplication is created it takes argv into account. If argv is
    None (default), it take arguments from :attr:`sys.argv`.

    If argv is given and a QApplication already exists, argv will have no
    effect.

    :param argv: optional arguments to QApplication. If the QApplication is
                 already initialized, argv will have no effect.

    Example::

        from qarbon.external.qt import QtGui
        from qarbon.qt.gui.application import Application

        app = Application()
        label = QtGui.QLabel("Hello, world!")
        label.show()
        app.exec_()

    :param properties: currently unused
    :return: the QApplication
    :rtype: QtGui.QApplication"""

    init_logging = properties.get('init_logging', False)
    if init_logging:
        log.initialize()

    from qarbon.external.qt import QtGui
    app = QtGui.QApplication.instance()
    if app is None:
        if argv is None:
            from sys import argv
        app = QtGui.QApplication(argv)
    elif argv:
        log.info("QApplication already initialized. argv will have no "
                 "effect")
    return app
Ejemplo n.º 10
0
def getQarbonIcon(icon_name):
    """Returns a QIcon for the given qarbon icon name.

    Example::

        from qarbon.external.qt import QtGui
        from qarbon.qt.qui.application import Application
        from qarbon.qt.gui.icon import getQarbonIcon

        app = Application()
        icon = getQarbonIcon(":/controls/collapse.png")
        button = QtGui.QPushButton(icon, "Collapse")
        button.show()
        app.exec_()

    :param icon_name: icon name
    :type icon_name: str
    :return: the QIcon corresponding to the given qarbon name. If the icon
             doesn't exist it returns a Null icon
    :rtype: QtGui.QIcon
    """
    return QtGui.QIcon(NAMESPACE + icon_name)
Ejemplo n.º 11
0
    def paintEvent(self, paintEvent):
        """Overwrite the paintEvent from QWidget to draw the pixmap"""
        pixmap = self._getPixmap()

        w, h = self.width(), self.height()
        painter = QtGui.QPainter(self)
        painter.setRenderHint(QtGui.QPainter.Antialiasing)
        pw, ph = pixmap.width(), pixmap.height()
        align = self._alignment
        hAlign = align & QtCore.Qt.AlignHorizontal_Mask
        vAlign = align & QtCore.Qt.AlignVertical_Mask
        x, y = 0, 0
        if hAlign & QtCore.Qt.AlignHCenter:
            x = (w - pw) / 2
        elif hAlign & QtCore.Qt.AlignRight:
            x = w - pw
        if vAlign & QtCore.Qt.AlignVCenter:
            y = (h - ph) / 2
        elif vAlign & QtCore.Qt.AlignBottom:
            y = h - ph
        x, y = max(0, x), max(0, y)
        painter.drawPixmap(x, y, pixmap)
Ejemplo n.º 12
0
    def create_single_input_panel(self, input_data):
#        style = Application().style()
        pixmap = Pixmap(QtGui.QStyle.SP_MessageBoxQuestion, 64)
        self.setIconPixmap(pixmap)

        self.setText(input_data['prompt'])

        data_type = input_data.get('data_type', 'String')
        is_seq = not isinstance(data_type, (str, unicode)) and \
                 isinstance(data_type, collections.Sequence)
        if is_seq:
            panel, getter = self.create_selection_panel(input_data)
        else:
            data_type_l = data_type.lower()
            creator = getattr(self, "create_" + data_type_l + "_panel",
                              self.create_custom_panel)
            if creator:
                panel, getter = creator(input_data)

        if panel is None:
            panel = QtGui.QLabel("Cannot create widget for data type '%s'"
                              % data_type)
            getter = lambda: None
        return panel, getter
Ejemplo n.º 13
0
 def changePixmap(self, name):
     self.w.pixmap = QtGui.QPixmap(name)
Ejemplo n.º 14
0
        def __init__(self, parent=None):
            QtGui.QWidget.__init__(self, parent)
            panel_l = QtGui.QVBoxLayout()
            self.setLayout(panel_l)
            panel_l.setContentsMargins(M, M, M, M)
            panel_l.setSpacing(M)

            w = PixmapWidget()
            display_panel = QtGui.QGroupBox("Pixmap Widget Display")
            display_l = QtGui.QHBoxLayout()
            display_l.setContentsMargins(M, M, M, M)
            display_l.setSpacing(M)
            display_panel.setLayout(display_l)
            display_l.addWidget(w, 1)

            control_panel = QtGui.QGroupBox("Control Panel")
            control_l = QtGui.QFormLayout()
            control_l.setContentsMargins(M, M, M, M)
            control_l.setSpacing(M)
            control_panel.setLayout(control_l)
            pixmap_widget = QtGui.QLineEdit()
            ratio_widget = QtGui.QComboBox()
            transformation_widget = QtGui.QComboBox()
            halign_widget = QtGui.QComboBox()
            valign_widget = QtGui.QComboBox()
            control_l.addRow("pixmap:", pixmap_widget)
            control_l.addRow("Aspect ratio mode:", ratio_widget)
            control_l.addRow("Transformation mode:", transformation_widget)
            control_l.addRow("Horiz. alignment:", halign_widget)
            control_l.addRow("Vert. alignment:", valign_widget)

            panel_l.addWidget(display_panel, 1)
            panel_l.addWidget(control_panel, 0)

            ratio_widget.addItems(["Ignore", "Keep", "Keep by expanding"])
            transformation_widget.addItem("Fast", QtCore.Qt.FastTransformation)
            transformation_widget.addItem("Smooth", QtCore.Qt.SmoothTransformation)
            halign_widget.addItem("Left", QtCore.Qt.AlignLeft)
            halign_widget.addItem("Center", QtCore.Qt.AlignHCenter)
            halign_widget.addItem("Right", QtCore.Qt.AlignRight)
            valign_widget.addItem("Top", QtCore.Qt.AlignTop)
            valign_widget.addItem("Center", QtCore.Qt.AlignVCenter)
            valign_widget.addItem("Bottom", QtCore.Qt.AlignBottom)

            pixmap_widget.textChanged.connect(self.changePixmap)
            ratio_widget.currentIndexChanged.connect(self.changeAspectRatio)
            halign_widget.currentIndexChanged.connect(self.changeAlignment)
            valign_widget.currentIndexChanged.connect(self.changeAlignment)

            self.w = w
            self.w_pixmap = pixmap_widget
            self.w_aspect_ratio = ratio_widget
            self.w_transformation = transformation_widget
            self.w_halign = halign_widget
            self.w_valign = valign_widget

            pixmap_widget.setText(qarbon.config.NAMESPACE + \
                                  ":/led/led_red_on.png")
            ratio_widget.setCurrentIndex(1)
            transformation_widget.setCurrentIndex(1)
            halign_widget.setCurrentIndex(0)
            valign_widget.setCurrentIndex(1)
Ejemplo n.º 15
0
def main():
    import sys
    import qarbon.config
    from qarbon.qt.gui.application import Application
    app = Application()

    M = 2

    class QPixmapWidgetTestPanel(QtGui.QWidget):

        def __init__(self, parent=None):
            QtGui.QWidget.__init__(self, parent)
            panel_l = QtGui.QVBoxLayout()
            self.setLayout(panel_l)
            panel_l.setContentsMargins(M, M, M, M)
            panel_l.setSpacing(M)

            w = PixmapWidget()
            display_panel = QtGui.QGroupBox("Pixmap Widget Display")
            display_l = QtGui.QHBoxLayout()
            display_l.setContentsMargins(M, M, M, M)
            display_l.setSpacing(M)
            display_panel.setLayout(display_l)
            display_l.addWidget(w, 1)

            control_panel = QtGui.QGroupBox("Control Panel")
            control_l = QtGui.QFormLayout()
            control_l.setContentsMargins(M, M, M, M)
            control_l.setSpacing(M)
            control_panel.setLayout(control_l)
            pixmap_widget = QtGui.QLineEdit()
            ratio_widget = QtGui.QComboBox()
            transformation_widget = QtGui.QComboBox()
            halign_widget = QtGui.QComboBox()
            valign_widget = QtGui.QComboBox()
            control_l.addRow("pixmap:", pixmap_widget)
            control_l.addRow("Aspect ratio mode:", ratio_widget)
            control_l.addRow("Transformation mode:", transformation_widget)
            control_l.addRow("Horiz. alignment:", halign_widget)
            control_l.addRow("Vert. alignment:", valign_widget)

            panel_l.addWidget(display_panel, 1)
            panel_l.addWidget(control_panel, 0)

            ratio_widget.addItems(["Ignore", "Keep", "Keep by expanding"])
            transformation_widget.addItem("Fast", QtCore.Qt.FastTransformation)
            transformation_widget.addItem("Smooth", QtCore.Qt.SmoothTransformation)
            halign_widget.addItem("Left", QtCore.Qt.AlignLeft)
            halign_widget.addItem("Center", QtCore.Qt.AlignHCenter)
            halign_widget.addItem("Right", QtCore.Qt.AlignRight)
            valign_widget.addItem("Top", QtCore.Qt.AlignTop)
            valign_widget.addItem("Center", QtCore.Qt.AlignVCenter)
            valign_widget.addItem("Bottom", QtCore.Qt.AlignBottom)

            pixmap_widget.textChanged.connect(self.changePixmap)
            ratio_widget.currentIndexChanged.connect(self.changeAspectRatio)
            halign_widget.currentIndexChanged.connect(self.changeAlignment)
            valign_widget.currentIndexChanged.connect(self.changeAlignment)

            self.w = w
            self.w_pixmap = pixmap_widget
            self.w_aspect_ratio = ratio_widget
            self.w_transformation = transformation_widget
            self.w_halign = halign_widget
            self.w_valign = valign_widget

            pixmap_widget.setText(qarbon.config.NAMESPACE + \
                                  ":/led/led_red_on.png")
            ratio_widget.setCurrentIndex(1)
            transformation_widget.setCurrentIndex(1)
            halign_widget.setCurrentIndex(0)
            valign_widget.setCurrentIndex(1)

        def changePixmap(self, name):
            self.w.pixmap = QtGui.QPixmap(name)

        def changeAspectRatio(self, i):
            v = QtCore.Qt.IgnoreAspectRatio
            if i == 1:
                v = QtCore.Qt.KeepAspectRatio
            elif i == 2:
                v = QtCore.Qt.KeepAspectRatioByExpanding
            self.w.setAspectRatioMode(v)

        def changeTransformationMode(self, i):
            v = QtCore.Qt.FastTransformation
            if i == 1:
                v = QtCore.Qt.SmoothTransformation
            self.w.setTransformationMode(v)

        def changeAlignment(self, i):
            halign = self.w_halign.itemData(self.w_halign.currentIndex())
            valign = self.w_valign.itemData(self.w_valign.currentIndex())
            self.w.alignment = halign | valign

    panel = QtGui.QWidget()
    layout = QtGui.QGridLayout()
    panel.setLayout(layout)
    layout.setContentsMargins(M, M, M, M)
    layout.setSpacing(M)
    p1 = QPixmapWidgetTestPanel()
    layout.addWidget(p1, 0, 0)
    panel.show()
    sys.exit(app.exec_())
Ejemplo n.º 16
0
 def contextMenuEvent(self, event):
     menu = QtGui.QMenu(self)
     refreshAction = QtGui.QAction(Icon("view-refresh"), "Refresh", self)
     refreshAction.triggered.connect(self.axis.refresh)
     menu.addAction(refreshAction)
     menu.popup(event.globalPos())
Ejemplo n.º 17
0
    def setQObject(self, qobject):
        """Sets the current QObject whose properties are to been seen by the
        editor.

        :param qobject: the new QObject (can be None)
        """
        ui = self.__ui
        superClassName = ""
        _class = ""
        className = ""
        isWidget = False
        propCount = 0
        if qobject is None:
            self.__qobject = None
        else:
            _class = qobject.__class__.__name__
            self.__qobject = weakref.ref(qobject)
            metaObject = qobject.metaObject()
            if metaObject is not None:
                className = metaObject.className()
                superClass = metaObject.superClass()
                if superClass is not None:
                    superClassName = superClass.className()
                isWidget = qobject.isWidgetType()
                propCount = metaObject.propertyCount()

        ui.classLineEdit.setText(_class)
        ui.classNameLineEdit.setText(className)
        ui.superClassNameLineEdit.setText(superClassName)
        ui.isWidgetLineEdit.setText(str(isWidget))
        ui.focusButton.setEnabled(isWidget)

        propTree = ui.propertiesTreeWidget

        QtCore.QObject.disconnect(
            propTree, QtCore.SIGNAL("itemChanged (QTreeWidgetItem*, int)"),
            self.__onPropertyTreeChanged)
        propTree.clear()
        if propCount == 0:
            return

        metaO, props = metaObject, []
        while True:
            first, last = metaO.propertyOffset(), metaO.propertyCount()
            if first < last:
                class_props = {}
                for p_index in range(first, last):
                    metaProp = metaObject.property(p_index)
                    class_props[metaProp.name()] = metaProp
                props.insert(0, (metaO, class_props))
            metaO = metaO.superClass()
            if metaO is None:
                break

        # build tree
        for metaO, props in props:
            topItem = QtGui.QTreeWidgetItem(propTree)
            topItem.setText(0, metaO.className())
            for prop_name in sorted(props.keys()):
                metaProp = props[prop_name]
                prop_type = metaProp.typeName()
                value = qobject.property(prop_name)
                prop_value = getPropertyValueDisplay(metaProp, value)
                columns = [prop_name, prop_type, prop_value]
                propItem = QtGui.QTreeWidgetItem(topItem, columns)
                propItem.setFlags(propItem.flags() | QtCore.Qt.ItemIsEditable)
                propItem.setData(2, QtCore.Qt.UserRole, prop_name)
                propItem.setData(2, QtCore.Qt.DisplayRole, value)
                propItem.setToolTip(2,
                                    getPropertyValueToolTip(metaProp, value))

        propTree.expandToDepth(1)
        propTree.headerItem()
        QtCore.QObject.connect(
            propTree, QtCore.SIGNAL("itemChanged (QTreeWidgetItem*, int)"),
            self.__onPropertyTreeChanged)
Ejemplo n.º 18
0
 def createStatusBar(self):
     sb = QtGui.QStatusBar()
     sb.setSizeGripEnabled(False)
     return sb
Ejemplo n.º 19
0
def main():
    class __DemoException(Exception):
        pass

    def s1():
        return s2()

    def s2():
        return s3()

    def s3():
        raise __DemoException("A demo exception occurred")

    def py_exc():
        try:
            s1()
        except:
            msgbox = ErrorDialog(*sys.exc_info())
            msgbox.exec_()

    def tg_exc():
        try:
            import PyTango
            PyTango.Except.throw_exception('TangoException',
                                           'A simple tango exception',
                                           'right here')
        except PyTango.DevFailed:
            msgbox = ErrorDialog(*sys.exc_info())
            msgbox.exec_()

    def tg_serv_exc():
        try:
            import PyTango
            dev = PyTango.DeviceProxy("sys/tg_test/1")
            dev.read_attribute("throw_exception")
        except PyTango.DevFailed:
            msgbox = ErrorDialog(*sys.exc_info())
            msgbox.exec_()
        except:
            msgbox = ErrorDialog(*sys.exc_info())
            msgbox.exec_()

    def py_tg_serv_exc():
        try:
            import PyTango
            PyTango.Except.throw_exception('TangoException',
                                           'A simple tango exception',
                                           'right here')
        except PyTango.DevFailed as df1:
            try:
                import StringIO
                origin = StringIO.StringIO()
                traceback.print_stack(file=origin)
                origin.seek(0)
                origin = origin.read()
                PyTango.Except.re_throw_exception(
                    df1, 'PyDs_Exception', 'DevFailed: A simple tango '
                    'exception', origin)
            except PyTango.DevFailed:
                msgbox = ErrorDialog(*sys.exc_info())
                msgbox.exec_()

    app = Application()
    app.setApplicationName("Message dialog demo")
    app.setApplicationVersion("1.0")

    panel = QtGui.QWidget()
    layout = QtGui.QVBoxLayout()
    panel.setLayout(layout)

    m1 = QtGui.QPushButton("Python exception")
    layout.addWidget(m1)
    m1.clicked.connect(py_exc)
    m2 = QtGui.QPushButton("Tango exception")
    layout.addWidget(m2)
    m2.clicked.connect(py_exc)
    layout.addWidget(m2)
    m3 = QtGui.QPushButton("Tango server exception")
    layout.addWidget(m3)
    m3.clicked.connect(tg_serv_exc)
    layout.addWidget(m3)
    m4 = QtGui.QPushButton("Python tango server exception")
    layout.addWidget(m4)
    m4.clicked.connect(py_tg_serv_exc)
    layout.addWidget(m4)

    panel.show()
    sys.exit(app.exec_())
Ejemplo n.º 20
0
 def resetPixmap(self):
     """Resets the pixmap for this widget."""
     self.setPixmap(QtGui.QPixmap())
Ejemplo n.º 21
0
def main():
    from qarbon.qt.gui.icon import getIcon

    app = Application()
    app.setStyleSheet(GROUPBOX_NEBULA_STYLESHEET)

    w = QtGui.QWidget()
    l = QtGui.QVBoxLayout()
    w.setLayout(l)

    panel = GroupBox()
    panel.title = "Database"
    content = QtGui.QWidget()
    contentLayout = QtGui.QFormLayout()
    content.setLayout(contentLayout)
    panel.setContent(content)
    contentLayout.addRow("&Host", QtGui.QLineEdit())
    contentLayout.addRow("&Port", QtGui.QLineEdit())
    l.addWidget(panel, 0)

    panel = GroupBox()
    panel.title = "Hello world"
    panel.titleIcon = getIcon("video-x-generic")
    panel.styleMap = {
        'title_start_color': 'rgb(255, 60, 60)',
        'title_stop_color': 'rgb(200, 0, 0)',
        'title_font_color': 'rgb(140, 0, 0)',
        'title_border_radius': '10px',
        'content_border_radius': '0px',
    }

    content = QtGui.QWidget()
    contentLayout = QtGui.QFormLayout()
    content.setLayout(contentLayout)
    panel.setContent(content)
    contentLayout.addRow("State", QtGui.QPushButton("Press here"))
    contentLayout.addRow("Status", QtGui.QLineEdit())
    contentLayout.addRow("Coment", QtGui.QLineEdit())
    contentLayout.addRow("Build", QtGui.QCheckBox())
    contentLayout.addRow("Upper limit", QtGui.QSpinBox())
    contentLayout.addRow("Lower limit", QtGui.QSpinBox())
    l.addWidget(panel, 0)

    panel = GroupBox()
    panel.title = "Hello world 2"
    panel.titleIcon = getIcon("network-server")
    panel.titleVisible = False
    content = QtGui.QWidget()
    contentLayout = QtGui.QFormLayout()
    content.setLayout(contentLayout)
    panel.setContent(content)
    contentLayout.addRow("Something", QtGui.QLineEdit())
    contentLayout.addRow("More", QtGui.QLineEdit())
    l.addWidget(panel, 0)

    panel = GroupBox()
    panel.title = "5"
    panel.titleIcon = getIcon("folder")
    content = QtGui.QWidget()
    contentLayout = QtGui.QVBoxLayout()
    content.setLayout(contentLayout)
    panel.setContent(content)
    panel2 = GroupBox()
    panel2.title = "5.1"
    panel2.titleIcon = getIcon("folder")
    panel2.titleHeight = 48

    content2 = QtGui.QWidget()
    contentLayout2 = QtGui.QFormLayout()
    content2.setLayout(contentLayout2)
    panel2.setContent(content2)
    contentLayout2.addRow("Something", QtGui.QLineEdit())
    contentLayout2.addRow("More", QtGui.QLineEdit())
    contentLayout.addWidget(panel2, 0)
    l.addWidget(panel, 0)

    l.addStretch(1)

    w.show()
    w.adjustSize()

    app.exec_()
    return w
Ejemplo n.º 22
0
def Application(argv=None, **kwargs):
    """Returns a QApplication.

    If the process has initialized before a QApplication it returns the
    existing instance, otherwise it creates a new one.

    When a QApplication is created it takes argv into account. If argv is
    None (default), it take arguments from :attr:`sys.argv`.

    If argv is given and a QApplication already exists, argv will have no
    effect.

    :param argv: optional arguments to QApplication. If the QApplication is
                 already initialized, argv will have no effect.

    Example::

        from qarbon.external.qt import QtGui
        from qarbon.qt.gui.application import Application

        app = Application()
        label = QtGui.QLabel("Hello, world!")
        label.show()
        app.exec_()

    :param kwargs: currently unused
    :return: the QApplication
    :rtype: QtGui.QApplication"""

    # It is important to initialize logging before Qt because Qt might
    # fire some log messages
    init_logging = kwargs.get('init_logging', False)
    if init_logging:
        log.initialize()

    from qarbon.external.qt import QtGui
    app = QtGui.QApplication.instance()
    if app is None:
        if argv is None:
            from sys import argv
        app = QtGui.QApplication(argv)

        init_application = kwargs.get('init_application', True)
        init_organization = kwargs.get('init_organization', True)
        if init_application:
            app_name = kwargs.get('application_name', config.APPLICATION_NAME)
            app.setApplicationName(app_name)
            app_version = kwargs.get('application_version',
                                     config.APPLICATION_VERSION)
            app.setApplicationVersion(app_version)
        if init_organization:
            org_name = kwargs.get('organization_name',
                                  config.ORGANIZATION_NAME)
            app.setOrganizationName(org_name)
            org_domain = kwargs.get('organization_domain',
                                    config.ORGANIZATION_DOMAIN)
            app.setOrganizationDomain(org_domain)

    elif argv:
        log.info("QApplication already initialized. argv will have no "
                 "effect")
    return app
Ejemplo n.º 23
0
 def roleIcon(self, taurus_role):
     return QtGui.QIcon()
Ejemplo n.º 24
0
class BaseModel(QtCore.QAbstractItemModel):
    """The base class for all Qt models."""

    ColumnNames = ()
    ColumnRoles = (),

    DftFont = QtGui.QFont("Mono", 8)

    def __init__(self, parent=None, data=None):
        QtCore.QAbstractItemModel.__init__(self, parent)
        # if qt < 4.6, beginResetModel and endResetModel don't exist. In this
        # case we set beginResetModel to be an empty function and endResetModel
        # to be reset.
        if not hasattr(QtCore.QAbstractItemModel, "beginResetModel"):
            self.beginResetModel = lambda: None
            self.endResetModel = self.reset
        self._data_src = None
        self._rootItem = None
        self._filters = []
        self._selectables = [self.ColumnRoles[0][-1]]
        self.setDataSource(data)

    def __getattr__(self, name):
        return getattr(self.dataSource(), name)

    def createNewRootItem(self):
        return BaseTreeItem(self, self.ColumnNames)

    def refresh(self, refresh_source=False):
        self.beginResetModel()
        self._rootItem = self.createNewRootItem()
        self.setupModelData(self.dataSource())
        self.endResetModel()

    def setupModelData(self, data):
        raise NotImplementedError("setupModelData must be implemented "
                                  "in %s" % self.__class__.__name__)

    def roleIcon(self, role):
        raise NotImplementedError("roleIcon must be implemented "
                                  "in %s" % self.__class__.__name__)

    def roleSize(self, role):
        raise NotImplementedError("roleSize must be implemented "
                                  "in %s" % self.__class__.__name__)

    def roleToolTip(self, role):
        raise NotImplementedError("roleToolTip must be implemented "
                                  "in %s" % self.__class__.__name__)

    def setDataSource(self, data_src):
        self._data_src = data_src
        self.refresh()

    def dataSource(self):
        return self._data_src

    def setSelectables(self, seq_elem_types):
        self._selectables = seq_elem_types

    def selectables(self):
        return self._selectables

    def role(self, column, depth=0):
        cr = self.ColumnRoles
        if column == 0:
            return cr[0][depth]
        return self.ColumnRoles[column]

    def columnCount(self, parent=QtCore.QModelIndex()):
        return len(self.ColumnRoles)

    def columnIcon(self, column):
        return self.roleIcon(self.role(column))

    def columnToolTip(self, column):
        return self.roleToolTip(self.role(column))

    def columnSize(self, column):
        role = self.role(column)
        s = self.roleSize(role)
        return s

    def pyData(self, index, role=QtCore.Qt.DisplayRole):
        if not index.isValid():
            return None

        item = index.internalPointer()

        ret = None
        if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole:
            ret = item.data(index)


#        elif role == Qt.Qt.CheckStateRole:
#            data = item.data(index)
#            if type(data) != bool:
#                data = str(data).lower() == 'true'
#            ret = Qt.Qt.Unchecked
#            if data == True:
#                ret = Qt.Qt.Checked
        elif role == QtCore.Qt.DecorationRole:
            ret = item.icon(index)
        elif role == QtCore.Qt.ToolTipRole:
            ret = item.toolTip(index)
        #elif role == Qt.Qt.SizeHintRole:
        #    ret = self.columnSize(column)
        elif role == QtCore.Qt.FontRole:
            ret = self.DftFont
        elif role == QtCore.Qt.UserRole:
            ret = item
        return ret

    def data(self, index, role=QtCore.Qt.DisplayRole):
        ret = self.pyData(index, role)
        return ret

    def _setData(self, index, pyobj, role=QtCore.Qt.EditRole):
        item = index.internalPointer()
        item.setData(index, pyobj)
        return True

    def flags(self, index):
        if not index.isValid():
            return 0

        ret = QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsDragEnabled

        item = index.internalPointer()
        column, depth = index.column(), item.depth()
        qrole = self.role(column, depth)

        if qrole in self.selectables():
            ret |= QtCore.Qt.ItemIsSelectable
        return ret

    def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
        ret = None
        if orientation == QtCore.Qt.Horizontal:
            if role == QtCore.Qt.TextAlignmentRole:
                ret = int(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
            elif role == QtCore.Qt.DisplayRole:
                ret = self.ColumnNames[section]
            elif role == QtCore.Qt.SizeHintRole:
                ret = QtCore.QSize(self.columnSize(section))
                ret.setHeight(24)
            elif role == QtCore.Qt.ToolTipRole:
                ret = self.columnToolTip(section)
            elif role == QtCore.Qt.DecorationRole:
                ret = self.columnIcon(section)

        return ret

    def index(self, row, column, parent=QtCore.QModelIndex()):
        if not self.hasIndex(row, column, parent):
            return QtCore.QModelIndex()
        if not parent.isValid():
            parentItem = self._rootItem
        else:
            parentItem = parent.internalPointer()
        childItem = parentItem.child(row)
        if childItem:
            return self.createIndex(row, column, childItem)
        return QtCore.QModelIndex()

    def parent(self, index):
        if not index.isValid():
            return QtCore.QModelIndex()

        childItem = index.internalPointer()
        parentItem = childItem.parent()

        if parentItem is None or parentItem == self._rootItem:
            return QtCore.QModelIndex()

        return self.createIndex(parentItem.row(), 0, parentItem)

    def rowCount(self, parent=QtCore.QModelIndex()):
        if parent.column() > 0:
            return 0

        if not parent.isValid():
            parentItem = self._rootItem
        else:
            parentItem = parent.internalPointer()
        if parentItem is None:
            return 0
        return parentItem.childCount()

    def hasChildren(self, parent=QtCore.QModelIndex()):
        if parent.column() > 0:
            return 0
        if not parent.isValid():
            parentItem = self._rootItem
        else:
            parentItem = parent.internalPointer()

        if parentItem is None:
            return False
        return parentItem.hasChildren()