Exemple #1
0
class UIBaseColors(ConstantGroup):
    RED = QtGui.QBrush(QtGui.QColor(230, 132, 131))
    LIGHT_SKY_BLUE = QtGui.QBrush(QtGui.QColor(135, 206, 250))
    DARK_YELLOW = QtGui.QBrush(QtGui.QColor(222, 158, 46))
Exemple #2
0
class UIPrimTypeColors(ConstantGroup):
    HAS_ARCS = UIBaseColors.DARK_YELLOW
    NORMAL = QtGui.QBrush(QtGui.QColor(227, 227, 227))
    INSTANCE = UIBaseColors.LIGHT_SKY_BLUE
    MASTER = QtGui.QBrush(QtGui.QColor(118, 136, 217))
Exemple #3
0
 def cropColor(self, color):
     self._cropColor = QtGui.QColor(*color)
     self.cropPen = QtGui.QPen(self._cropColor, 3, QtCore.Qt.DotLine)
Exemple #4
0
import uuid
import logging
import pprint
from functools import partial
from slither import api
from slither.core import executor
from qt import QtGui, QtWidgets
from vortex.ui.graphics import graphicsdatamodel
from vortex.ui import application
import attributewidgets

logger = logging.getLogger(__name__)

ATTRIBUTETYPEMAP = {
    'Quaternion': {
        "color": QtGui.QColor(126.999945, 24.999944999999997,
                              24.999944999999997),
        "widget": None
    },
    'color': {
        "color": QtGui.QColor(22.999980000000015, 255, 255)
    },
    'matrix4': {
        "color":
        QtGui.QColor(174.99987000000002, 130.00001999999998,
                     114.99990000000001)
    },
    'multi': {
        "color": QtGui.QColor(255, 255, 255)
    },
    'vector2D': {
        "color": QtGui.QColor(147.000105, 102.0, 156.000075)
Exemple #5
0
class Panel(QtWidgets.QGraphicsWidget):
    color = QtGui.QColor(0.0, 0.0, 0.0, 125)

    def __init__(self,
                 objectModel,
                 ioType,
                 acceptsContextMenu=False,
                 parent=None):
        super(Panel, self).__init__(parent=parent)
        self.model = objectModel
        self.ioType = ioType
        layout = QtWidgets.QGraphicsLinearLayout(parent=self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(1)
        layout.setOrientation(QtCore.Qt.Vertical)
        self.attributeContainer = graphicitems.ItemContainer(parent=self)
        layout.addItem(self.attributeContainer)
        self.setSizePolicy(
            QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding,
                                  QtWidgets.QSizePolicy.Expanding))
        self.acceptsContextMenu = acceptsContextMenu

        self.setLayout(layout)
        self.setFlags(self.flags() & QtCore.Qt.ItemIsSelectable)
        self.setZValue(100)
        self.refresh()

    def refresh(self):
        currentModel = self.model
        if currentModel is None:
            return
        self.attributeContainer.clear()
        for attr in currentModel.attributes(self.ioType == "Input",
                                            self.ioType == "Output", 3):
            self.addAttribute(attr)

    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.RightButton and self.acceptsContextMenu:
            self._contextMenu(QtGui.QCursor.pos())
            return
        super(Panel, self).mousePressEvent(event)

    def addAttribute(self, attribute):
        plug = plugwidget.PlugContainer(attribute,
                                        parent=self.attributeContainer)
        layout = plug.layout()
        if attribute.isInput() and self.ioType == "Input":
            if attribute.isArray() or attribute.isCompound():
                plug.inCrossItem.show()
            plug.inCircle.show()
            plug.outCircle.hide()
            #     # insert the inCircle to the far right
            layout.insertItem(3, plug.inCircle)
            layout.insertItem(2, plug.inCrossItem)
            # we switch this around for panels because the model input would be connected to another input
            # making it difficult to which is the start point and end point of a connection
            plug.inCircle.ioType = "Output"
            layout.insertStretch(2, 1)
        else:
            if attribute.isArray() or attribute.isCompound():
                plug.outCrossItem.show()
            plug.outCircle.show()
            plug.inCircle.hide()
            #     # insert the outCircle to the far left
            layout.insertItem(0, plug.outCircle)
            layout.insertItem(1, plug.outCrossItem)
            layout.itemAt(layout.count() - 1)
            plug.inCircle.ioType = "Input"
            plug.setTextAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)

        # swap the layout alignment
        plug.setInputAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
        plug.layout().setAlignment(
            plug.inCrossItem, QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
        plug.layout().setAlignment(
            plug.outCrossItem, QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
        plug.setOutputAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
        self.attributeContainer.addItem(plug)

    def attributeItem(self, attributeModel):
        for attr in iter(self.attributeContainer.items()):
            if attr.model == attributeModel:
                return attr

    def paint(self, painter, option, widget):
        rect = self.windowFrameRect()
        painter.fillRect(rect, self.color)
        painter.setPen(QtGui.QPen(self.color, 3))
        super(Panel, self).paint(painter, option, widget)

    def _contextMenu(self, pos):
        app = self.scene().uiApplication
        menu = app.createContextMenu(app.currentModel)
        if menu:
            menu.exec_(pos)
            self.refresh()

    def handleConnectionDrop(self, model):
        if not model.objectModel.canCreateAttributes():
            return
        print "drop", self.ioType, model
Exemple #6
0
class ConnectionEdge(QtWidgets.QGraphicsPathItem):
    """Class to deal with the Connection path between two plugs
    You set the style of the path with setLineStyle(QtCore.Qt.Style)
    """
    contextMenuRequested = QtCore.Signal(object)
    defaultColor = QtGui.QColor(138, 200, 0)
    selectedColor = QtGui.QColor(255, 255, 255)
    hoverColor = QtGui.QColor(255, 255, 255)
    CUBIC = 0
    LINEAR = 1

    def __init__(self,
                 source,
                 destination=None,
                 curveType=CUBIC,
                 color=defaultColor):
        super(ConnectionEdge, self).__init__()
        self.curveType = curveType
        self._sourcePlug = source
        self._destinationPlug = destination
        self._sourcePoint = source.center()
        self._destinationPoint = destination.center(
        ) if destination is not None else None
        self.defaultPen = QtGui.QPen(color, 1.25, style=QtCore.Qt.DashLine)
        self.defaultPen.setDashPattern([1, 2, 2, 1])
        self.selectedPen = QtGui.QPen(self.selectedColor,
                                      1.7,
                                      style=QtCore.Qt.DashLine)
        self.selectedPen.setDashPattern([1, 2, 2, 1])

        self.hoverPen = QtGui.QPen(self.hoverColor,
                                   1.7,
                                   style=QtCore.Qt.DashLine)
        self.selectedPen.setDashPattern([1, 2, 2, 1])
        self.hovering = False

        self.setPen(self.defaultPen)
        self.setZValue(-1)
        self.setFlags(self.ItemIsFocusable | self.ItemIsSelectable
                      | self.ItemIsMovable)
        self.setCurveType(curveType)
        self.update()

    def setWidth(self, width):
        lineWidth = width * 1.25
        self.defaultPen.setWidth(width)
        self.selectedPen.setWidth(lineWidth)
        self.hoverPen.setWidth(lineWidth)

    def setCurveType(self, cType):
        if cType == "Linear":
            self.setAsLinearPath()
        elif cType == "Cubic":
            self.setAsCubicPath()

    def setLineStyle(self, qStyle):

        self.defaultPen.setStyle(qStyle)
        self.selectedPen.setStyle(qStyle)
        self.hoverPen.setStyle(qStyle)

    def setAsLinearPath(self):
        path = QtGui.QPainterPath()
        path.moveTo(self._sourcePoint)
        path.lineTo(self._destinationPoint)
        self.curveType = ConnectionEdge.LINEAR
        self.setPath(path)

    def setAsCubicPath(self):
        path = QtGui.QPainterPath()

        path.moveTo(self._sourcePoint)
        dx = self._destinationPoint.x() - self._sourcePoint.x()
        dy = self._destinationPoint.y() - self._sourcePoint.y()
        ctrl1 = QtCore.QPointF(self._sourcePoint.x() + dx * 0.50,
                               self._sourcePoint.y() + dy * 0.1)
        ctrl2 = QtCore.QPointF(self._sourcePoint.x() + dx * 0.50,
                               self._sourcePoint.y() + dy * 0.9)
        path.cubicTo(ctrl1, ctrl2, self._destinationPoint)
        self.curveType = ConnectionEdge.CUBIC
        self.setPath(path)

    def hoverLeaveEvent(self, event):
        super(ConnectionEdge, self).hoverEnterEvent(event)
        self.hovering = False
        self.update()

    def hoverEnterEvent(self, event):
        super(ConnectionEdge, self).hoverEnterEvent(event)
        self.hovering = True
        self.update()

    def paint(self, painter, option, widget):

        if self.isSelected():
            painter.setPen(self.selectedPen)
        elif self.hovering:
            painter.setPen(self.hoverPen)
        else:
            painter.setPen(self.defaultPen)
        painter.drawPath(self.path())

    def updatePosition(self):
        """Update the position of the start and end of the edge
        """
        self._destinationPoint = self.destinationPlug.center()
        self._sourcePoint = self.sourcePlug.center()
        self.updatePath()

    def updatePath(self):
        if self.curveType == ConnectionEdge.CUBIC:
            self.setAsCubicPath()
        else:
            self.setAsLinearPath()

    def connect(self, src, dest):
        """Create a connection between the src plug and the destination plug
        :param src: Plug
        :param dest: Plug
        :return: None
        """
        if not src and dest:
            return
        self._sourcePlug = src
        self._destinationPlug = dest
        src.addConnection(self)
        dest.addConnection(self)

    def disconnect(self):
        """Remove the connection between the source and destination plug
        """
        self._sourcePlug.removeConnection(self)
        self._destinationPlug.removeConnection(self)
        self._sourcePlug = None
        self._destinationPlug = None

    @property
    def sourcePoint(self):
        """Return the source point
        :return: QtCore.QPointF()
        """
        return self._sourcePoint

    @sourcePoint.setter
    def sourcePoint(self, point):
        """Sets the source point and updates the path
        :param point: QtCore.QPointF
        """
        self._sourcePoint = point
        self.updatePath()

    @property
    def destinationPoint(self):
        """return the destination point
        :return: QtCore.QPointF
        """
        return self._destinationPoint

    @destinationPoint.setter
    def destinationPoint(self, point):
        """Sets the destination point and updates the path
        :param point: QtCore.QPointF
        """
        self._destinationPoint = point
        self.updatePath()

    @property
    def sourcePlug(self):
        """Return the source plug
        :return: Plug
        """
        return self._sourcePlug

    @sourcePlug.setter
    def sourcePlug(self, plug):
        """Sets the source plug and update the path
        :param plug: Plug
        """
        self._sourcePlug = plug
        self._sourcePoint = plug.center()
        self._sourcePlug.parentObject().connections.add(plug)
        self.updatePath()

    @property
    def destinationPlug(self):
        """Returns the destination plug
        :return: Plug
        """
        return self._destinationPlug

    @destinationPlug.setter
    def destinationPlug(self, plug):
        self._destinationPlug = plug
        self._destinationPoint = plug.center()
        self._destinationPlug.parentObject().connections.add(self)
        self.updatePath()

    def close(self):
        """
        """
        if self.scene() is not None:
            self.scene().removeItem(self)

    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            event.accept()
            if self.isSelected():
                self.setSelected(False)
            else:
                self.setSelected(True)

            self.update()
        self._destinationPoint = event.pos()

    def mouseMoveEvent(self, event):
        self._destinationPoint = self.mapToScene(event.pos())

    def contextMenuEvent(self, event):
        menu = QtWidgets.QMenu(self)

        self.contextMenuRequested.emit(menu)
        menu.exec_(event.scenePos())
        event.setAccepted(True)
Exemple #7
0
 def _stroke(self, painter, x, y, width, height):
     rect = QtCore.QRect(x, y, width, height)
     painter.setPen(self._defaultPen)
     painter.setBrush(QtGui.QBrush(QtGui.QColor(0.0, 0.0, 0.0, 0.0)))
     painter.drawRect(rect)
Exemple #8
0
class UIPropertyValueSourceColors(ConstantGroup):
    FALLBACK = UIBaseColors.DARK_YELLOW
    TIME_SAMPLE = QtGui.QBrush(QtGui.QColor(177, 207, 153))
    DEFAULT = UIBaseColors.LIGHT_SKY_BLUE
    NONE = QtGui.QBrush(QtGui.QColor(140, 140, 140))
    VALUE_CLIPS = QtGui.QBrush(QtGui.QColor(230, 150, 230))
Exemple #9
0
class GraphicsText(QtWidgets.QGraphicsWidget):
    _font = QtGui.QFont("Roboto-Bold.ttf", 8)
    _font.setLetterSpacing(QtGui.QFont.PercentageSpacing, 110)
    _fontMetrics = QtGui.QFontMetrics(_font)
    textChanged = QtCore.Signal(str)
    _color = QtGui.QColor(200, 200, 200)

    def __init__(self, text, parent=None):
        super(GraphicsText, self).__init__(parent=parent)
        self._previousText = text
        self._item = QtWidgets.QGraphicsTextItem(text, parent=self)
        self._item.setDefaultTextColor(self._color)
        self._item.setFont(self._font)
        self._item.document().contentsChanged.connect(self.onTextChanged)
        self.setPreferredSize(self.size)
        self.setSizePolicy(
            QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
                                  QtWidgets.QSizePolicy.Fixed))
        self._item.setFlags(QtWidgets.QGraphicsItem.ItemIsSelectable
                            | QtWidgets.QGraphicsItem.ItemIsFocusable
                            | QtWidgets.QGraphicsItem.ItemIsMovable)
        self._item.setTextInteractionFlags(QtCore.Qt.TextEditorInteraction)
        option = self._item.document().defaultTextOption()
        option.setWrapMode(QtGui.QTextOption.NoWrap)
        self._item.document().setDefaultTextOption(option)
        self.allowHoverHighlight = False
        self.setAcceptHoverEvents(True)
        self.adjustSize()

    def onTextChanged(self):
        newText = self._item.document().toPlainText()
        if newText != self._previousText:
            self._previousText = newText
            self.textChanged.emit(newText)

    def setTextFlags(self, flags):
        self._item.setFlags(flags)

    @property
    def font(self):
        return self._item.font()

    @font.setter
    def font(self, value):
        return self._item.setFont(value)

    @property
    def text(self):
        return self._item

    @text.setter
    def text(self, text):
        self._item.setPlainText(text)
        self._item.update()
        self.setPreferredSize(
            QtCore.QSizeF(self._item.textWidth(),
                          self._font.pointSizeF() + 10))

    def onResize(self, width):
        fmWidth = self._fontMetrics.width(self.item.toPlainText())
        newWidth = min(fmWidth, width)
        if width > fmWidth:
            newWidth = width

        self._item.setTextWidth(newWidth)
        self.setPreferredSize(newWidth, self.textHeight())

    @property
    def size(self):
        return QtCore.QSizeF(self._item.textWidth(), self.height)

    @property
    def height(self):
        return self._item.document().documentLayout().documentSize().height(
        ) + 2

    @property
    def color(self):
        return self._item.defaultTextColor()

    @color.setter
    def color(self, color):
        self._item.setDefaultTextColor(color)
        self.update()

    def highlight(self):
        highlightColor = self.color.lighter(150)
        self.color = highlightColor

    def unhighlight(self):
        self.color = self._color

    def hoverEnterEvent(self, event):
        if self.allowHoverHighlight:
            self.highlight()
        super(GraphicsText, self).hoverEnterEvent(event)

    def hoverLeaveEvent(self, event):
        if self.allowHoverHighlight:
            self.unhighlight()
        super(GraphicsText, self).hoverLeaveEvent(event)
Exemple #10
0
    def iconColorizedLayered(cls,
                             iconNames,
                             size=16,
                             colors=None,
                             iconScaling=None,
                             tintColor=None):
        """ Layers multiple icons with various colours into one qicon. Maybe can replace icon colorized

        :param iconNames: the icon name from the library. Allow string or list for convenience
        :type iconNames: list or basestring
        :param size: the uniform icon size
        :type size: int
        :param colors: 3 tuple for the icon color
        :type colors: list of tuple
        :return: the colorized icon
        :param overlayName: The name of the icon that will be overlayed on top of the original icon
        :param overlayColor: The colour of the overlay
        :rtype: QtGui.QIcon
        """
        defaultSize = 1

        if isinstance(iconNames, basestring):
            iconNames = [iconNames]
        elif isinstance(iconNames, list):
            iconNames = list(iconNames)  # copy

        if isinstance(iconScaling, list):
            iconScaling = list(iconScaling)  # copy

        if not isinstance(colors, list):
            colors = [colors]
        else:
            colors = list(colors)  # copy

        if iconNames is []:
            print "WARNING: iconNames cannot be none for iconColorizedLayered"
            p = QtGui.QPixmap(16, 16)
            p.fill(QtGui.QColor(255, 255, 255))

        # Fill out the colours to match the length of iconNames
        if colors is None or (len(iconNames) > len(colors)):
            colors = colors or []
            colors += [None] * (len(iconNames) - len(colors))

        # Fill out the sizes to match the length of iconNames
        if iconScaling is None or len(iconNames) > len(iconScaling):
            iconScaling = iconScaling or []
            iconScaling += [defaultSize] * (len(iconNames) - len(iconScaling))

        iconLargest = cls.icon(iconNames.pop(0), -1)

        if not iconLargest:
            return iconLargest

        origSize = iconLargest.availableSizes()[0]
        col = colors.pop(0)
        scale = iconScaling.pop(0)
        if col is not None:
            pixmap = cls.colorPixmap(iconLargest.pixmap(origSize * scale), col)
        else:
            pixmap = iconLargest.pixmap(origSize * scale)

        # Layer the additional icons
        for i, name in enumerate(iconNames):
            if name is None:
                continue
            overlayIcon = cls.icon(name, -1)
            overlayPixmap = overlayIcon.pixmap(origSize * iconScaling[i])
            cls.addOverlay(pixmap, overlayPixmap, colors[i])

        # Tint
        if tintColor is not None:
            cls.tint(pixmap, tintColor)

        pixmap = pixmap.scaled(QtCore.QSize(size,
                                            size), QtCore.Qt.KeepAspectRatio,
                               QtCore.Qt.SmoothTransformation)

        return QtGui.QIcon(pixmap)
Exemple #11
0
class UIPrimTreeColors(ConstantGroup):
    SELECTED = QtGui.QBrush(QtGui.QColor(189, 155, 84))
    SELECTED_HOVER = QtGui.QBrush(QtGui.QColor(227, 186, 101))
    ANCESTOR_OF_SELECTED = QtGui.QBrush(QtGui.QColor(189, 155, 84, 50))
    ANCESTOR_OF_SELECTED_HOVER = QtGui.QBrush(QtGui.QColor(189, 155, 84, 100))
    UNSELECTED_HOVER = QtGui.QBrush(QtGui.QColor(70, 70, 70))
Exemple #12
0
    def insertRow(self, rowdata):
        r = self.rowCount()
        super(TableWidget, self).insertRow(r)
        self.definerow(r)
        self.fillrow(r, rowdata)

    def setColor(self, row, column):
        color = qg.QColorDialog.getColor(qc.Qt.green, self)
        if color.isValid():
            print(color, row, column)
            self.fillfunction[column](row, column, color)

if __name__ == '__main__':
    import sys
    app = qg.QApplication(sys.argv)
    data = [['Row 1', 0, 0, qg.QColor(0, 0, 255)],
            ['Row 2', 0, 0, qg.QColor(0, 255, 0)],
            ['Row 3', 0, 0, qg.QColor(255, 0, 0)],
            ['Row 4', 0, 0, qg.QColor(127, 127, 0)]]

    #    data= numpy.array(data)
    w = TableWidget(['Name', 'V', 'E', 'Color'])
    #
    w.insertrows(data)
    #    for ii,rowdata in enumerate(data):
    #        w.insertRow(rowdata)
    #    for ii,rowdata in enumerate(data):
    #        w.fillrow(ii,rowdata)
    #
    w.show()
    sys.exit(app.exec_())
Exemple #13
0
class LogRecordModel(QtCore.QAbstractTableModel):

    foreground_map = {
        logging.ERROR: QtGui.QColor(255, 0, 0),
        logging.CRITICAL: QtGui.QColor(255, 255, 255),
    }

    background_map = {
        logging.DEBUG: QtGui.QColor(192, 255, 255),
        logging.WARNING: QtGui.QColor(255, 255, 192),
        #logging.ERROR: QtGui.QColor(255, 192, 192),
        logging.CRITICAL: QtGui.QColor(255, 0, 0),
    }

    style_map = {
        logging.ERROR: 'bold',
        logging.CRITICAL: 'bold',
    }

    def __init__(self, parent, records, columns, capacity=0):
        super(LogRecordModel, self).__init__(parent)
        self._records = records
        self._columns = columns
        self.font = parent.font()
        self._capacity = capacity

    def columnCount(self, index):
        if index.isValid():
            result = 0
        else:
            visible = [col for col in self._columns if col.visible]
            result = len(visible)
        return result

    def rowCount(self, index):
        if self._records is None or index.isValid():
            result = 0
        else:
            result = len(self._records)
        return result

    def data(self, index, role=Qt.DisplayRole):
        result = None
        if index.isValid():
            record = self._records[index.row()]
            if role == Qt.DisplayRole:
                try:
                    viscols = [c for c in self._columns if c.visible]
                    col = viscols[index.column()]
                    v = getattr(record, col.name)
                    result = v
                except Exception:
                    logger.exception('Error')
            elif role == Qt.BackgroundColorRole:
                result = self.background_map.get(record.levelno)
            elif role == Qt.TextColorRole:
                result = self.foreground_map.get(record.levelno)
            elif role == Qt.FontRole:
                QFont = QtGui.QFont
                result = None
                style = self.style_map.get(record.levelno)
                if style:
                    result = QFont(self.font)
                    if 'bold' in style:
                        result.setWeight(QFont.Bold)
                    if 'italic' in style:
                        result.setStyle(QFont.StyleItalic)
            elif role == MessageRole: # special role used for searching
                result = record.message
        return result

    def headerData(self, section, orientation, role):
        result = None
        if orientation == Qt.Horizontal and role == Qt.DisplayRole:
            try:
                visible = [col.title for col in self._columns if col.visible]
                result = visible[section]
            except IndexError:
                pass
        return result

    def add_record(self, record):
        pos = len(self._records)
        if self._capacity and pos >= self._capacity:
            self.beginRemoveRows(invindex, 0, 0)
            self._records.popleft()
            self.endRemoveRows()
            pos -= 1
        self.beginInsertRows(invindex, pos, pos)
        self._records.append(record)
        self.endInsertRows()

    def clear(self):
        if hasattr(self._records, 'clear'):
            self._records.clear()
        else:
            del self._records[:]
        self.reset()

    def get_record(self, pos):
        return self._records[pos]
Exemple #14
0
class NavigationGraphicsView(QtGui.QGraphicsView):
    '''Graphics view for dataset navigation.

    The view usually displays an auto-scalled low resolution overview
    of the scene with a red box indicating the area currently displayed
    in the high resolution view.

    :SIGNALS:

        * :attr:`mousePressed`
        * :attr:`mouseMoved`

    '''

    BOXCOLOR = QtGui.QColor(QtCore.Qt.red)

    #: SIGNAL: it is emitted when a mouse button is presses on the view
    #:
    #: :param point:
    #:     the scene position
    #: :param mousebutton:
    #:     the ID of the pressed button
    #: :param dragmode:
    #:     current darg mode
    #:
    #: :C++ signature: `void mousePressed(QPointF, Qt::MouseButtons,
    #:                                    QGraphicsView::DragMode)`
    mousePressed = QtCore.Signal(QtCore.QPointF, QtCore.Qt.MouseButtons,
                                 QtGui.QGraphicsView.DragMode)

    #: SIGNAL: it is emitted when the mouse is moved on the view
    #:
    #: :param point:
    #:     the scene position
    #: :param mousebutton:
    #:     the ID of the pressed button
    #: :param dragmode:
    #:     current darg mode
    #:
    #: :C++ signature: `void mouseMoved(QPointF, Qt::MouseButtons,
    #:                                    QGraphicsView::DragMode)`
    mouseMoved = QtCore.Signal(QtCore.QPointF, QtCore.Qt.MouseButtons,
                               QtGui.QGraphicsView.DragMode)

    def __init__(self, parent=None, **kwargs):
        super(NavigationGraphicsView, self).__init__(parent, **kwargs)
        self._viewbox = None
        self._autoscale = True
        self.setMouseTracking(True)

    def getbox(self):
        return self._viewbox

    def setbox(self, box):
        assert isinstance(box, (QtCore.QRect, QtCore.QRectF))
        self._viewbox = box
        if self.isVisible():
            # @WARNING: calling "update" on the scene causes a repaint of
            #           *all* attached views and for each view the entire
            #           exposedRect is updated.
            #           Using QGraphicsView.invalidateScene with the
            #           QtGui.QGraphicsScene.ForegroundLayer parameter
            #           should be faster and repaint only one layer of the
            #           current view.

            # @TODO: check
            #self.invalidateScene(self.sceneRect(),
            #                     QtGui.QGraphicsScene.ForegroundLayer)
            self.scene().update()

    viewbox = property(getbox, setbox, doc='viewport box in scene coordinates')

    def drawForeground(self, painter, rect):
        if not self.viewbox:
            return

        pen = painter.pen()
        try:
            box = self.viewbox.intersected(self.sceneRect())
            painter.setPen(self.BOXCOLOR)
            painter.drawRect(box)
            #painter.drawConvexPolygon(self.viewbox) #@TODO: check
        finally:
            painter.setPen(pen)

    def fitInView(self, rect=None, aspectRatioMode=QtCore.Qt.KeepAspectRatio):
        if not rect:
            scene = self.scene()
            if scene:
                rect = scene.sceneRect()
            else:
                return
        QtGui.QGraphicsView.fitInView(self, rect, aspectRatioMode)

    def _getAutoscale(self):
        return self._autoscale

    def _setAutoscale(self, flag):
        self._autoscale = bool(flag)
        if self._autoscale:
            self.fitInView()
        else:
            self.setMatrix(QtGui.QMatrix())
            self.update()

    autoscale = property(_getAutoscale, _setAutoscale)

    def resizeEvent(self, event):
        if self.autoscale:
            self.fitInView()
        return QtGui.QGraphicsView.resizeEvent(self, event)

    # @TODO: use event filters
    def mousePressEvent(self, event):
        pos = self.mapToScene(event.pos())
        self.mousePressed.emit(pos, event.buttons(), self.dragMode())
        return QtGui.QGraphicsView.mousePressEvent(self, event)

    def mouseMoveEvent(self, event):
        pos = self.mapToScene(event.pos())
        self.mouseMoved.emit(pos, event.buttons(), self.dragMode())
        return QtGui.QGraphicsView.mouseMoveEvent(self, event)
Exemple #15
0
class BaseDataSource(QtCore.QObject):
    enabledColor = QtGui.QColor(200, 200, 220)
    disabledColor = enabledColor.darker(200)

    def __init__(self, headerText=None, model=None, parent=None):
        super(BaseDataSource, self).__init__()
        self._parent = parent
        self.children = []
        self.model = model
        self._headerText = headerText or ""

    def width(self):
        return 0

    def userObject(self, index):
        if index in xrange(self.rowCount()):
            return self.children[index]

    def userObjects(self):
        return self.children

    def setUserObjects(self, objects):
        pass

    def isRoot(self):
        """Determines if this item is the root of the tree

        :return:
        :rtype:
        """
        return True if not self.parent else False

    def rowCount(self):
        """Returns the total row count for the dataSource defaults to the len of the dataSource children

        :rtype: int
        """
        return len(self.children)

    def columnCount(self):
        return 1

    def parentSource(self):
        """Returns the parent of this node
        :rtype: Node
        """
        return self._parent

    def index(self):
        if self._parent is not None and self._parent.children:
            return self._parent.children.index(self)
        return 0

    def child(self, index):
        """

        :param index: the column index
        :type index: int
        """
        if index in xrange(self.rowCount()):
            return self.children[index]

    def insertChild(self, index, child):
        if child not in self.children:
            self.children.insert(index, child)
            child.parent = self

    def append(self, child):
        if child not in self.children:
            self.children.append(child)

    def setData(self, index, value):
        """Sets the text value of this node at the specified column

        :param index: The column index
        :type index: int
        :return: the new text value for this nodes column index
        :rtype: str
        """
        pass

    def data(self, index):
        """The text for this node or column. index parameter with a value of 0 is
        the first column.

        :param index: The column index for the item
        :type index: int
        :return: the column text
        :rtype: str
        """
        return ""

    def toolTip(self, index):
        """The tooltip for the index.

        :param index: The column index for the item
        :type index: int
        :rtype: str
        """
        model = self.model
        if model is None:
            return ""
        columns = list(model.columnDataSources)
        msg = self.headerText(index) + ":" + str(self.data(index)) + "\n"
        for i in columns:
            msg += i.headerText(index) + ":" + str(i.data(self, index)) + "\n"
        return msg

    def icon(self, index):
        """The icon for the index.

        :param index: The column index for the item
        :type index: int
        :rtype: QtGui.QIcon
        """
        pass

    def headerIcon(self):
        """Returns the column header icon

        :rtype: QtGui.QIcon
        """
        return QtGui.QIcon()

    def headerText(self, index):
        """Returns the column header text

        :return: the header value
        :rtype: str
        """
        return self._headerText

    def headerVerticalText(self, index):
        """The Vertical header text, if the return type is None then no text is displayed, an empty string will
        produce a gap in the header.

        :param index: The column index for the item
        :type index: int
        :rtype: str or None

        """
        return None

    def headerVerticalIcon(self, index):
        """The Vertical header icon

        :param index: The column index for the item
        :type index: int
        :rtype: QtGui.QIcon()
        """
        return QtGui.QIcon()

    def isEditable(self, index):
        """Determines if this node can be editable e.g set text. Defaults to False

        :param index: The column index for the item
        :type index: int
        :return: whether or not this node is editable, defaults to False
        :rtype: bool
        """
        return True

    def isEnabled(self, index):
        """Determines if this node is enabled

        :param index: The column index for the item
        :type index: int
        :return: whether or not this node is enabled, defaults to True
        :rtype: bool
        """
        return True

    def supportsDrag(self, index):
        """

        :param index: the column index
        :type index: int
        """
        return False

    def supportsDrop(self, index):
        """

        :param index: the column index
        :type index: int
        """
        return False

    def mimeTypes(self):
        pass

    def mimeData(self, indices):

        return QtCore.QMimeData()

    def dropMimeData(self, index):
        """

        :param index: the column index
        :type index: int
        """
        return False

    def mimeText(self, index):
        """

        :param index: the column index
        :type index: int
        """
        return

    def isSelectable(self, index):
        """

        :param index: the column index
        :type index: int
        """
        return True

    def foregroundColor(self, index):
        """

        :param index: the column index
        :type index: int
        """
        if self.isEnabled(index):
            return self.enabledColor
        return self.disabledColor

    def backgroundColor(self, index):
        """
        :param index: the column index
        :type index: int
        """
        return None

    def displayChangedColor(self, index):
        """
        :param index: the column index
        :type index: int
        """
        return None

    def alignment(self, index):
        """

        :param index: the column index
        :type index: int
        """
        return QtCore.Qt.AlignVCenter

    def font(self, index):
        """

        :param index: the column index
        :type index: int
        """
        return

    def isCheckable(self, index):
        """

        :param index: the column index
        :type index: int
        """
        return False

    def insertColumnDataSources(self, index, count):
        """

        :param index: the column index
        :type index: int
        """
        return False

    def removeColumnDataSources(self, index, count):
        """

        :param index: the column index
        :type index: int
        """
        return False

    def removeRowDataSource(self, index):
        """

        :param index: the column index
        :type index: int
        """
        return False

    def removeRowDataSources(self, index, count):
        """

        :param index: the column index
        :type index: int
        """
        return False

    def insertRowDataSources(self, index, count):
        """

        :param index: the column index
        :type index: int
        """
        return None

    def insertRowDataSource(self, index):
        """

        :param index: the column index
        :type index: int
        """
        return False

    def onVerticalHeaderSelection(self, index):
        """Triggered by the table view(if this source is attached to one) when the vertical header is clicked
        :param index: the row index
        :type index: int
        """
        pass

    def contextMenu(self, menu):
        pass

    def sort(self, index=0, order=QtCore.Qt.DescendingOrder):
        """This sort function purpose is for sorting the data by column.

        :param index: the column index to sort
        :type index: int
        :param order: The Qt order
        :type order: int
        """
        def element(key):
            return key[1]

        toSort = [(obj, self.data(i))
                  for i, obj in enumerate(self.userObjects())]

        if order == QtCore.Qt.DescendingOrder:
            results = [i[0] for i in sorted(toSort, key=element, reverse=True)]
        else:
            results = [i[0] for i in sorted(toSort, key=element)]
        self.setUserObjects(results)