コード例 #1
0
 def _init_content(self, direction, collapsed):
     content = QFrame(self)
     content_layout = QBoxLayout(direction)
     content_layout.setAlignment(Qt.AlignTop)
     content.setLayout(content_layout)
     content.setVisible(not collapsed)
     return content
コード例 #2
0
    def __init__(self):
        super(Window, self).__init__()
        box = QBoxLayout(QBoxLayout.LeftToRight, self)
        self.resize(1200, 800)

        def canvas_on_close_handler(_1, _2):
            self.close()
        _context.canvas.set_on_close_handler(canvas_on_close_handler)
        box.addWidget(_context.canvas.native)
        
        rightBoxWidget = QWidget()
        rightBox = QBoxLayout(QBoxLayout.TopToBottom, rightBoxWidget)
        rightBox.setAlignment(Qt.AlignTop)
        box.addWidget(rightBoxWidget)

        tensor_view_selector = TensorRankViewSelector()
        rightBox.addWidget(tensor_view_selector)

        #button = QPushButton('Change View', self)
        #button.setToolTip('Change View Port')
        #rightBox.addWidget(button)

        xyzRangeSelector = XYZRangeSelector()
        rightBox.addWidget(xyzRangeSelector)

        tw_container = TensorRankShower()
        rightBox.addWidget(tw_container)

        self.show()
コード例 #3
0
ファイル: _gui.py プロジェクト: git-is-good/ten_compr
    def __init__(self):
        super(Window, self).__init__()
        box = QBoxLayout(QBoxLayout.LeftToRight, self)
        self.resize(1200, 800)

        tensor_display_context = TensorDisplayContext(_tensor_data)

        def canvas_on_close_handler(_1, _2):
            self.close()
        tensor_display_context.canvas.set_on_close_handler(canvas_on_close_handler)
        box.addWidget(tensor_display_context.canvas.native)
        
        rightBoxWidget = QWidget()
        rightBox = QBoxLayout(QBoxLayout.TopToBottom, rightBoxWidget)
        rightBox.setAlignment(Qt.AlignTop)
        box.addWidget(rightBoxWidget)

        tensor_view_selector = TensorRankViewSelector()
        rightBox.addWidget(tensor_view_selector)

        xyzRangeSelector = XYZRangeSelector(_tensor_data)
        rightBox.addWidget(xyzRangeSelector)

        tw_container = TensorRankShower(_tensor_data)
        rightBox.addWidget(tw_container)

#        esc_shortcut = QShortcut(self)
#        esc_shortcut.activated.connect(self.close)
        
        self.show()
コード例 #4
0
    def __init__(self, function_list, plot_canvas, parent=None):
        super().__init__(parent)

        # Prevent closing
        self.setFeatures(QDockWidget.DockWidgetMovable
                         | QDockWidget.DockWidgetFloatable)

        # Initialize layout
        contents = QWidget()
        layout = QBoxLayout(QBoxLayout.LeftToRight, contents)
        layout.setContentsMargins(10, 0, 10, 20)
        self.setWidget(contents)

        # Add function selection dropdown to layout
        label_combobox = QLabel()
        label_combobox.setText("<b>Function:</b>")
        layout.addWidget(label_combobox)
        layout.setAlignment(label_combobox, Qt.AlignCenter)
        combobox_function = QComboBox()

        # Add functions to dropdown, create map so we can associate values back
        # with original function objects
        self._function_map = {}
        for function in function_list:
            item_text = f"{function.name}: {function.description}"
            combobox_function.addItem(item_text)
            self._function_map[item_text] = function
        layout.addWidget(combobox_function)

        # Add "A" parameter slider to layout
        slider_a = FancySlider("A", -10.0, 10.0, 20)
        layout.addWidget(slider_a)

        # Add "B" parameter slider to layout
        slider_b = FancySlider("B", -10.0, 10.0, 20)
        layout.addWidget(slider_b)

        # Event handlers: update the plot whenever a relevant change is made
        combobox_function.currentTextChanged.connect(self.updatePlot)
        slider_a.valueChanged.connect(self.updatePlot)
        slider_b.valueChanged.connect(self.updatePlot)

        # Event handler: rotate our dock based on where the user puts it
        self.dockLocationChanged.connect(self.updateDockOrientation)

        # Save some elements for later access
        self._layout = layout
        self._combobox_function = combobox_function
        self._slider_a = slider_a
        self._slider_b = slider_b
        self._plot_canvas = plot_canvas

        # Render initial state
        self.updatePlot()
コード例 #5
0
 def __init__(self, parent):
     super(LostGameWindow, self).__init__(parent)
     mainLayout = QBoxLayout(QBoxLayout.TopToBottom)
     mainLayout.setAlignment(Qt.AlignCenter)
     self.quitButton = QPushButton("<font color=\"white\">OK</font>")
     self.quitButton.released.connect(self.hide)
     self.text = QLabel("Lorem ipsum dolor sit amet")
     self.text.setWordWrap(True)
     self.setStyleSheet("background-color: black;")
     mainLayout.addWidget(self.text)
     mainLayout.addWidget(self.quitButton)
     self.setLayout(mainLayout)
     self.setFixedSize(400, 300)
コード例 #6
0
    def __init__(self, parent: QWidget):

        super().__init__(parent)

        # roi selection
        self.roi_button = RoiSelectionButton(self)

        # layout
        layout = QBoxLayout(QBoxLayout.LeftToRight)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(self.roi_button)
        layout.setAlignment(self.roi_button, Qt.AlignLeft)
        self.setLayout(layout)
        self.adjustSize()
        self.setStyleSheet("border: 1px solid red")
コード例 #7
0
    def __init__(self, qtpy):
        super().__init__(qtpy)
        self.setWindowTitle(qtpy.language.get("app_name"))

        self.header = Header(qtpy)

        self.main_widget = QWidget()
        layout = QBoxLayout(QBoxLayout.TopToBottom)
        layout.setAlignment(Qt.AlignTop)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(self.header)
        self.main_widget.setLayout(layout)

        self.setCentralWidget(self.main_widget)

        apply_theme(self.qtpy.client, self.main_widget)
コード例 #8
0
ファイル: ToolBarArea.py プロジェクト: lihaochen910/Candy
class CToolBarArea(QWidget):
    signalDragStart = pyqtSignal()
    signalDragEnd = pyqtSignal()
    signalItemDropped = pyqtSignal(CToolBarAreaItem, QWidget, int)

    def __init__(self, parent, orientation):
        super().__init__(parent)
        self.editor = parent
        self.orientation = orientation
        self.dropTargetSpacer = None
        self.actionContextPosition = QPoint()
        self.isLocked = False

        if self.orientation == Qt.Horizontal:
            self.layout_ = QBoxLayout(QBoxLayout.LeftToRight)
        else:
            self.layout_ = QBoxLayout(QBoxLayout.TopToBottom)

        self.layout_.setSpacing(0)
        self.layout_.setContentsMargins(0, 0, 0, 0)

        self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
        self.setLayout(self.layout_)
        self.setAcceptDrops(True)
        self.setContextMenuPolicy(Qt.CustomContextMenu)

        # print ( "CToolBarArea.__init__", parent )

    def getOrientation(self):
        return self.orientation

    def getToolBars(self):
        items = getAllItems(self)
        toolBarItems = []

        for item in items:
            if item.getType() != CToolBarAreaType.ToolBar:
                continue
            toolBarItems.append(item)

        return toolBarItems

    def getLargestItemMinimumSize(self):
        minSize = self.minimumSize()
        items = getAllItems(self)
        for item in items:
            minSize = minSize.expandedTo(item.getMinimumSize())

        return minSize

    def setOrientation(self, orientation):
        self.orientation = orientation
        self.layout_.setDirection(QBoxLayout.LeftToRight if self.orientation ==
                                  Qt.Horizontal else QBoxLayout.TopToBottom)
        self.updateLayoutAlignment()

        items = getAllItems(self)
        for item in items:
            item.setOrientation(self.orientation)

    def setActionContextPosition(self, actionContextPosition):
        self.actionContextPosition = actionContextPosition

    def fillContextMenu(self, menu):
        pass

    def addItem(self, item, targetIndex):
        item.signalDragStart.connect(self.onDragStart)
        item.signalDragEnd.connect(self.onDragEnd)
        item.setOrientation(self.orientation)
        item.setLocked(self.isLocked)
        self.layout_.insertWidget(targetIndex, item)
        item.setArea(self)

    def addToolBar(self, toolBar, targetIndex):
        self.addItem(CToolBarItem(self, toolBar, self.orientation),
                     targetIndex)

    def addSpacer(self, spacerType, targetIndex):
        self.addItem(CSpacerItem(self, spacerType, self.orientation),
                     targetIndex)
        if spacerType == CSpacerType.Expanding:
            self.layout_.setAlignment(0)

    def removeItem(self, item):
        self.layout_.removeWidget(item)
        item.signalDragStart.disconnect(self)
        item.signalDragEnd.disconnect(self)

        self.updateLayoutAlignment(item)

    def deleteToolBar(self, toolBarItem):
        if self.isAncestorOf(toolBarItem):
            qWarning("Trying to remove non-owned toolbar from area")
            return
        toolBarItem.deleteLater()

    def hideAll(self):
        items = getAllItems(self)
        for item in items:
            item.setVisible(False)

    def findToolBarByName(self, szToolBarName):
        toolBarItems = self.findChildren(CToolBarItem, "",
                                         Qt.FindDirectChildrenOnly)
        for toolBarItem in toolBarItems:
            if toolBarItem.getName() == szToolBarName:
                return toolBarItem

        print("Toolbar not found: %s" % szToolBarName)
        return None

    def setLocked(self, isLocked):
        self.isLocked = isLocked
        items = getAllItems(self)
        for item in items:
            item.setLocked(isLocked)

    def getState(self):
        pass

    def setState(self, state):
        pass

    def dragEnterEvent(self, event):
        print("CToolBarArea.dragEnterEvent", event)
        dragDropData = CDragDropData.fromMimeData(event.mimeData())
        if dragDropData.hasCustomData(CToolBarAreaItem.getMimeType()):
            byteArray = dragDropData.getCustomData(
                CToolBarAreaItem.getMimeType())
            stream = QDataStream(byteArray)
            value = None
            stream >> value
            draggedItem = value if isinstance(value,
                                              CToolBarAreaItem) else None

            if not self.parentWidget().isAncestorOf(draggedItem):
                return

            event.acceptProposedAction()

            self.setProperty("dragHover", True)
            self.style().unpolish(self)
            self.style().polish(self)

    def dragMoveEvent(self, event):
        dragDropData = CDragDropData.fromMimeData(event.mimeData())
        if dragDropData.hasCustomData(CToolBarAreaItem.getMimeType()):
            targetIndex = self.getPlacementIndexFromPosition(
                self.mapToGlobal(event.pos()))
            event.acceptProposedAction()

            if self.dropTargetSpacer and targetIndex == self.layout_.indexOf(
                    self.dropTargetSpacer):
                return

            byteArray = dragDropData.getCustomData(
                CToolBarAreaItem.getMimeType())
            stream = QDataStream(byteArray)
            value = None
            stream >> value
            draggedItem = value if isinstance(value,
                                              CToolBarAreaItem) else None

            if not self.parentWidget().isAncestorOf(draggedItem):
                return

            spacerWidth = draggedItem.width()
            spacerHeight = draggedItem.height()

            if draggedItem.getOrientation() != self.orientation:
                tempWidth = spacerWidth
                spacerWidth = spacerHeight
                spacerHeight = tempWidth

            if self.dropTargetSpacer == None:
                self.dropTargetSpacer = QSpacerItem(spacerWidth, spacerHeight,
                                                    QSizePolicy.Fixed,
                                                    QSizePolicy.Fixed)
            else:
                spacerIndex = self.layout_.indexOf(self.dropTargetSpacer)
                if spacerIndex == targetIndex - 1 or (
                        targetIndex == -1
                        and spacerIndex == self.layout_.count() - 1):
                    return

                self.removeDropTargetSpacer()
                self.dropTargetSpacer = QSpacerItem(spacerWidth, spacerHeight,
                                                    QSizePolicy.Fixed,
                                                    QSizePolicy.Fixed)

            self.layout_.insertSpacerItem(targetIndex, self.dropTargetSpacer)

    def dragLeaveEvent(self, event):
        self.removeDropTargetSpacer()

        self.setProperty("dragHover", False)
        self.style().unpolish(self)
        self.style().polish(self)

    def dropEvent(self, event):
        dragDropData = CDragDropData.fromMimeData(event.mimeData())
        if dragDropData.hasCustomData(CToolBarAreaItem.getMimeType()):
            event.acceptProposedAction()
            byteArray = dragDropData.getCustomData(
                CToolBarAreaItem.getMimeType())
            stream = QDataStream(byteArray)
            value = None
            stream >> value
            item = value if isinstance(value, CToolBarAreaItem) else None

            targetIndex = -1

            if self.dropTargetSpacer:
                targetIndex = self.layout_.indexOf(self.dropTargetSpacer)

                containerIndex = self.layout_.indexOf(item)
                if containerIndex >= 0 and containerIndex < targetIndex:
                    targetIndex -= 1

                self.removeDropTargetSpacer()

            if targetIndex >= self.layout_.count():
                targetIndex = -1

            self.signalItemDropped.emit(item, self, targetIndex)

    def customEvent(self, event):
        pass

    def paintEvent(self, event):
        styleOption = QStyleOption()
        styleOption.initFrom(self)
        painter = QPainter(self)
        self.style().drawPrimitive(QStyle.PE_Widget, styleOption, painter,
                                   self)

    def onDragStart(self, item):
        self.updateLayoutAlignment(item)
        item.setVisiable(False)
        self.signalDragStart.emit()

    def onDragEnd(self, item):
        item.setVisiable(True)
        self.signalDragEnd.emit()

    def removeDropTargetSpacer(self):
        if self.dropTargetSpacer:
            self.layout_.removeItem(self.dropTargetSpacer)
            self.dropTargetSpacer = None

    def indexForItem(self, item):
        return self.layout_.indexOf(item)

    def moveItem(self, item, destinationIndex):
        sourceIndex = self.indexForItem(item)
        if sourceIndex == destinationIndex:
            return
        self.layout_.insertWidget(destinationIndex, item)

    def updateLayoutAlignment(self, itemToBeRemoved=None):
        spacers = self.findChildren(CSpacerItem, "", Qt.FindDirectChildrenOnly)
        expandingSpacers = []
        for spacer in spacers:
            if spacer.getSpacerType() == CSpacerType.Expanding:
                expandingSpacers.append(spacer)

        if len(expandingSpacers) == 0 or len(expandingSpacers) != 0 or (
                len(expandingSpacers) == 1
                and expandingSpacers[0] == itemToBeRemoved):
            if self.orientation == Qt.Horizontal:
                self.layout_.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
            else:
                self.layout_.setAlignment(Qt.AlignTop | Qt.AlignHCenter)

    def getItemAtPosition(self, globalPos):
        object = QApplication.widgetAt(globalPos)
        if object == None or object == self:
            return None

        item = object if isinstance(object, CToolBarAreaItem) else None
        while item == None and object.parent():
            object = object.parent()
            item = object if isinstance(object, CToolBarAreaItem) else None

        return item

    def getPlacementIndexFromPosition(self, globalPos):
        targetIndex = -1
        item = self.getItemAtPosition(globalPos)

        if item == None:
            localPos = self.mapFromGlobal(globalPos)
            if self.dropTargetSpacer:
                geom = self.dropTargetSpacer.geometry()
                if geom.contains(localPos):
                    targetIndex = self.layout_.indexOf(self.dropTargetSpacer)

            return targetIndex

        targetIndex = self.indexForItem(item)

        if self.orientation == Qt.Horizontal and item.mapFromGlobal(
                globalPos).x() > item.width() / 2:
            targetIndex += 1
        elif self.orientation == Qt.Vertical and item.mapFromGlobal(
                globalPos).y() > item.height() / 2:
            targetIndex += 1

        if targetIndex >= self.layout_.count():
            targetIndex = -1

        return targetIndex
コード例 #9
0
class dicomImage2DdisplayWidget(QWidget):
    addSeedsSignal = pyqtSignal(bool)
    def __init__(self, **kwargs):
        super(dicomImage2DdisplayWidget, self).__init__()
        self._face = kwargs.get('face', 0)
        self._datas = kwargs.get('datas', 0)
        self._Spacing = kwargs.get('spacing', None)
        self._low_hu = kwargs.get("low_hu", -1150)
        self._high_hu = kwargs.get("high_hu", 3250)
        self._axis = 0
        #===============Seeds information============================
        self.seedsColors = []
        self.baseImageSize = 512
        self.regionDrawMod = 0
        self.drawLayer = []

        #===============Regioin draw tool parmeter===================
        self.drawPanterbegin = QPoint()
        self.drawPanterEnd = QPoint()
        self.posX = 0
        self.posY = 0

        #===============Init UI======================================
        self.initUI()


    def initUI(self):
        self.setGeometry(0, 0, self.baseImageSize, self.baseImageSize)

        self.viewLayout = None
        self.imLable = QLabel(self)
        self.imLable.setScaledContents(True)
        self.imData = None

        self.topLable = QLabel(self)
        self.downLable = QLabel(self)
        self.imLable.resize(self.width(), self.height())

        self.initDicomParameter()
        pass

    def initDicomParameter(self):
        #============================SetDataParameter===========================
        self._color_table = [qRgb(i, i, i) for i in range(64)]
        self.datas = self._datas.copy()
        self.faceWindowV = self.faceWindowH = max(self.datas.shape)

        #============================ChangeFaceSize=============================
        self.xSpacing, self.ySpacing, self.zSpacing = self._Spacing

        #============================OperationMod===============================
        self.OperationMod = 0
        self.facePlane = ['mainFaceplane', 'leftFaceplane', 'frontFaceplane']
        self.idxSlice = 100

        self.currentFace = self.facePlane[self._face]
        #============================RegionGrowingParameter=====================
        self.PosXY = [150, 75]
        # self.seedList = [(self.PosXY[0], self.PosXY[1])]
        self.seedList = []

        self.seedSelectNum = 0

        self.LowAndUpper = [10, 3000]
        self.regionArea = []
        self.regionDrawSize = 5

        self.idxSlicelimt = self.datas.shape[0]
        # print(self.datas.shape[0])
        #=======================================================================
        self.initOperationButton()
        self.initDisplayfacePlane()
        self.choiceOpreationMod()

        pass

    def initOperationButton(self):
        self.facePlanes = QComboBox(self)
        self.facePlanes.addItem(self.facePlane[0])
        self.facePlanes.addItem(self.facePlane[1])
        self.facePlanes.addItem(self.facePlane[2])
        self.facePlanes.setCurrentIndex(self._face)
        # self.facePlanes.activated[str].connect(self.faceItem_Choice)
        self.facePlanes.currentTextChanged.connect(self.faceItem_Choice)
        self.facePlanes.keyPressEvent = self.customComboxKeyEvent
        self.facePlanes.move((self.width() - self.facePlanes.width()), 0)

        #==================================Active keyBoard event without combobox=======================
        # shorcut = QShortcut(QKeySequence(Qt.Key_F), self.facePlanes, activated=self.useforTestKeyEvent)
        #===============================================================================================

        #================================== Contrul region seed up and low range =======================
        regionWide = QRangeSlider(self)
        regionWide.setMax(255)
        regionWide.setMin(0)
        regionWide.setStart(150)
        regionWide.setEnd(255)
        regionWide.setRange(0, 255)
        regionWide.setDrawValues(True)
        regionWide.setBackgroundStyle('background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #222, stop:1 #333);')
        regionWide.handle.setStyleSheet('background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #8EE5EE, stop:1 #393);')
        regionWide.startValueChanged.connect(self.rangeSliderStartVolue)
        regionWide.endValueChanged.connect(self.rangeSliderEndVolue)
        #===============================================================================================

        self.modCombox = QComboBox(self)
        self.modCombox.addItem('Normal')
        self.modCombox.addItem('Region')
        self.modCombox.setCurrentIndex(self.OperationMod)
        # self.modCombox.activated[str].connect(self.mod_Choice)
        self.modCombox.currentTextChanged.connect(self.mod_Choice)
        self.modCombox.keyPressEvent = self.customComboxKeyEvent
        self.modCombox.move((self.width() - self.facePlanes.width() - self.modCombox.width()), 0)

        self.layerScrollBar = QScrollBar(Qt.Horizontal, self)
        self.layerScrollBar.setGeometry(0, 0, 128, 5)
        self.layerScrollBar.setMinimum(0)
        self.layerScrollBar.setMaximum(min(self.datas.shape))
        self.layerScrollBar.setValue(0)
        self.layerScrollBar.sliderMoved.connect(self.selectLayer)

        self.BaseBoxLayout = QBoxLayout(QBoxLayout.TopToBottom)
        self.BaseBoxLayout.addWidget(self.layerScrollBar, 0)
        self.BaseBoxLayout.addWidget(regionWide, 1)
        self.BaseBoxLayout.setAlignment(Qt.AlignTop)


        self.secondBoxLayout = QBoxLayout(QBoxLayout.LeftToRight)
        self.secondBoxLayout.addLayout(self.BaseBoxLayout)
        self.secondBoxLayout.addWidget(self.modCombox)
        self.secondBoxLayout.addWidget(self.facePlanes)
        self.secondBoxLayout.setAlignment(Qt.AlignTop)

        self.groupbox = QGroupBox(self)
        self.groupbox.setGeometry(28, -64, 512, 64)
        self.groupbox.setLayout(self.secondBoxLayout)

        self.showButton = QPushButton(self)
        self.showButton.setGeometry(0, 0, 16, 16)
        self.showButton.clicked.connect(self.playAnimation)


        self.initAnimation()
        pass

    def setGroup_pos(self, apos):
        self.groupbox.move(apos.x(), apos.y())
        pass

    def setSeedsColor(self, lists):

        # self.seedList.clear()
        # self.seedsColors.clear()
        # for i in range(0, len(colorList)):
        #     self.seedsColors.append(colorList[i][0])
        #     self.seedList.append(colorList[i][1])
        self.seedsColors.append(lists[0])
        self.seedList.append(lists[1])
        print('seedList:', self.seedList)

        pass

    def selectSeedinList(self, num):
        # tmpS = self.seedList[num]
        # tmpC = self.seedsColors[num]
        self.seedSelectNum = num
        # print(self.seedsColors)
        # print(self.seedList)
        # print('number is :', num)
        # print(tmpC, tmpS)
        pass

    def removeSeedinList(self, num):
        self.seedList.remove(self.seedList[num])
        self.choiceDisplayMod()
        pass

    def rangeSliderStartVolue(self, event):
        self.LowAndUpper[0] = event
        self.choiceDisplayMod()
        pass

    def rangeSliderEndVolue(self, event):
        self.LowAndUpper[1] = event
        self.choiceDisplayMod()
        pass

    def viewSeedinList(self, event):
        if event[0] == True:
            print('Open eye is:', event[1])
        elif event[0] == False:
            print('Close eye is:', event[1])
        else:
            print('viewSeedinList error.....')

        pass

    def initAnimation(self):
        self.isBoardshow = False
        xAxis = self.groupbox.pos().x()
        yAxis = self.groupbox.height()

        self.groupBoxAnim = QPropertyAnimation(self, b'pos')
        self.groupBoxAnim.setDuration(200)
        self.groupBoxAnim.setStartValue(QPointF(xAxis, -yAxis))
        # self.anim.setKeyValueAt(0.5, QPointF(0, 10))
        # self.anim.setKeyValueAt(0.8, QPointF(0, 80))
        self.groupBoxAnim.setEndValue(QPointF(xAxis, 0))

        self.reverGroupBoxAnim = QPropertyAnimation(self, b'pos')
        self.reverGroupBoxAnim.setDuration(200)
        self.reverGroupBoxAnim.setStartValue(QPointF(xAxis, 0))
        self.reverGroupBoxAnim.setEndValue(QPointF(xAxis, -yAxis))

        pass

    def playAnimation(self):
        print('-----PlayAnimation-----')
        if self.isBoardshow == False:
            self.reverGroupBoxAnim.stop()
            self.groupBoxAnim.start()
            self.isBoardshow = True
        elif self.isBoardshow == True:
            self.groupBoxAnim.stop()
            self.reverGroupBoxAnim.start()
            self.isBoardshow = False
        pass
    pos = pyqtProperty(QPointF, fset=setGroup_pos)

    def selectLayer(self, event):
        self.idxSlice = self.layerScrollBar.value()
        self.choiceDisplayMod()
        pass

    def sliderval(self):
        self._low_hu = self.lowHusBar.value()
        self._high_hu = self.heighHusBar.value()
        self.choiceDisplayMod()
        pass

    def mod_Choice(self, event):
        if event == 'Normal':
            self.OperationMod = 0
        elif event == 'Region':
            self.OperationMod = 1
        self.choiceOpreationMod()
        pass

    def initDisplayfacePlane(self):
        if self._face == 0:
            self.topfaceView()
        elif self._face == 1:
            self.leftfaceView()
        elif self._face == 2:
            self.frontfaceView()
        pass


    def faceItem_Choice(self, faceEvent):

        if faceEvent == self.facePlane[0]:
            self.topfaceView()
            self.currentFace = self.facePlane[0]
            print('main view')
        elif faceEvent == self.facePlane[1]:
            self.leftfaceView()
            self.currentFace = self.facePlane[1]
            print('left view')
        elif faceEvent == self.facePlane[2]:
            self.frontfaceView()
            self.currentFace = self.facePlane[2]
            print('front view')

        self.choiceOpreationMod()
        self.getResizeEvent(self.width(), self.height())
        pass

    #==========================MakeSureDisplayMod=============================
    def choiceDisplayMod(self):
        if self.OperationMod == 0:
            self.drawNomralArea()
        elif self.OperationMod == 1:
            self.drawGrowingArea()
        pass
    #=========================================================================

    def choiceOpreationMod(self):
        if self.OperationMod == 0:
            self.imLable.mouseMoveEvent = self.normalModMouseMoveEvent
        elif self.OperationMod == 1:
            self.imLable.mouseMoveEvent = self.regionModMouseMoveEvent
            self.imLable.mousePressEvent = self.regionModMousePressEvent
            self.imLable.mouseReleaseEvent = self.regionModMouseReleasedEvent

            self.imLable.wheelEvent = self.regionGrowingWheelEvent
        self.choiceDisplayMod()
        pass



    def topfaceView(self):
        self.datas = self._datas.copy()
        self.idxSlicelimt = self.datas.shape[0]
        self.faceWindowH = self.faceWindowV = self.width()
        tmpPalete = QPalette()
        tmpPalete.setColor(QPalette.Background, QColor(0, 0, 0))
        self.setPalette(tmpPalete)
        #=======================Init drawLayer===================
        self.drawLayer = np.full(self.datas.shape, 0)
        print('topfaceView:', self.drawLayer.shape)

        pass

    def leftfaceView(self):

        self.datas = self._datas.copy()
        self.datas = np.rot90(self.datas, -1)
        self.datas = np.rot90(self.datas,  axes=(0, 2))
        self.idxSlicelimt = self.datas.shape[0]

        self.setScaleSize(max(self.datas.shape), min(self.datas.shape))

        tmpPalete = QPalette()
        tmpPalete.setColor(QPalette.Background, QColor(0, 0, 0))
        self.setPalette(tmpPalete)

        #=======================Init drawLayer===================
        self.drawLayer = np.full(self.datas.shape, 0)
        print('leftfaceView:', self.drawLayer.shape)

        pass


    def frontfaceView(self):
        self.datas = self._datas.copy()
        self.datas = np.rot90(self.datas, -1)
        self.idxSlicelimt = self.datas.shape[0]

        width = self.datas.shape[0]
        height = self.datas.shape[1]
        depth = self.datas.shape[2]
        self.setScaleSize(max(width, height, depth), min(width, height, depth))

        tmpPalete = QPalette()
        tmpPalete.setColor(QPalette.Background, QColor(0, 0, 0))
        self.setPalette(tmpPalete)

        #=======================Init drawLayer===================
        self.drawLayer = np.full(self.datas.shape, 0)
        print('frontfaceView:', self.drawLayer.shape)

        pass

    def drawNomralArea(self):
        self.idxSlice = np.clip(self.idxSlice, 0, self.idxSlicelimt -1)
        self.imData = self.datas[self.idxSlice]
        self.displayDicomImage()
        pass

    def drawGrowingArea(self):
        self.imgOriginal = SimpleITK.GetImageFromArray(self.datas[self.idxSlice])
        self.imgWhiteMatter = SimpleITK.ConnectedThreshold(image1=self.imgOriginal,
                                                           seedList=self.seedList,
                                                           lower=self.LowAndUpper[0],
                                                           upper=self.LowAndUpper[1],
                                                           replaceValue=1,
                                                           )
        self.regionArea = SimpleITK.GetArrayFromImage(self.imgWhiteMatter)

        #================if use draw or eraser====================
        if np.sum(self.drawLayer[self.idxSlice] != 0) != 0:
            self.regionDrawLayerCombinEvent()

        self.drawGrowingAreaContour()
        pass

    def drawGrowingAreaContour(self):
        foreColorvalue = 1
        self.imgWhiteMatter = SimpleITK.GetImageFromArray(self.regionArea)
        self.imgWhiteMatterNoHoles = SimpleITK.VotingBinaryHoleFilling(image1=self.imgWhiteMatter,
                                                                       radius=[2] * 3,
                                                                       majorityThreshold=50,
                                                                       backgroundValue=0,
                                                                       foregroundValue=foreColorvalue)
        regionContour = SimpleITK.LabelContour(self.imgWhiteMatterNoHoles)
        # tmpWmatter = self.imgWhiteMatter
        # regionContour = tmpWmatter | regionContour
        tmpImage = SimpleITK.LabelOverlay(self.imgOriginal, regionContour)
        regionContourArray = SimpleITK.GetArrayFromImage(tmpImage)
        self.imData = regionContourArray
        self.displayDicomImage()

        pass

    #==============================Key board event ============================================
    def customComboxKeyEvent(self, event):
        print('ComboxKeyEvent')
        pass

    def useforTestKeyEvent(self):
        print('just test combobox key event')
        # self.displayDicomImage()
        pass


    #==============================Use for display dicom image=================================
    def displayDicomImage(self):
        if self.imData is not None:
            raw_data = self.imData
            shape = self.imData.shape
            # maxNum = max(shape)
            # minNum = min(shape)
            raw_data[raw_data < 0] = 0
            raw_data[raw_data > 255] = 255
            if len(shape) >= 3:
                data = raw_data
                #=================用于调节对比度的方法=======================
                # data = (raw_data - self._low_hu) / self.window_width * 256
                # print('---------Update3d--------')
                #===========================================================
                data = data.astype(np.int8)
                tmpImage = QImage(data, shape[1], shape[0], shape[1] * shape[2], QImage.Format_RGB888)
                pixmap = QPixmap.fromImage(tmpImage)
                # pixmap = pixmap.scaled(self.faceWindowH , self.faceWindowV )
                # pixmap = pixmap.scaled(self.xSpacing, self.zSpacing)
                # pixmap = pixmap.scaled(1024, 128)
                self.imLable.setPixmap(pixmap)
            elif len(shape) < 3:
                data = raw_data
                # data = (raw_data - self._low_hu) / self.window_width * 256
                # print('---------Update2d---------')
                data = data.astype(np.int8)
                tmpImage = QImage(data, shape[1], shape[0],  QImage.Format_Grayscale8)
                tmpImage.setColorTable(self._color_table)
                pixmap = QPixmap.fromImage(tmpImage)
                # pixmap = pixmap.scaled(self.faceWindowH, self.faceWindowV)
                # pixmap = pixmap.scaled(self.xSpacing, self.zSpacing)
                # pixmap = pixmap.scaled(1024, 128)
                self.imLable.setPixmap(pixmap)
        pass

    def normalModMouseMoveEvent(self, event):
        if event.buttons() == Qt.LeftButton:
            xAxis = event.pos().x()
            yAxis = event.pos().y()
        self.choiceDisplayMod()
        pass

#=============================Region draw layer operation==========================================
    def regionDrawLayerEvent(self, x, y, value):
        self.regionArea[y - self.regionDrawSize:y + self.regionDrawSize, x - self.regionDrawSize:x + self.regionDrawSize] = value
        self.drawLayer[self.idxSlice] = self.regionArea
        pass

    def regionDrawLayerCombinEvent(self):
        self.regionArea = self.drawLayer[self.idxSlice].astype(np.uint8)
        pass

#=============================Region mod mouse Press and released event============================
    def regionModMousePressEvent(self, event):

        if event.buttons() == Qt.LeftButton and self.regionDrawMod != 0:
            xAxis = event.pos().x()
            yAxis = event.pos().y()
            if xAxis >= 0 and yAxis >= 0:
                tmpX = math.floor(xAxis * (self.baseImageSize / self.imLable.width()))
                tmpY = math.floor(yAxis * (self.baseImageSize / self.imLable.height()))
                if self.regionDrawMod == 1:
                    self.regionDrawLayerEvent(tmpX, tmpY, 1)
                elif self.regionDrawMod == 2:
                    self.regionDrawLayerEvent(tmpX, tmpY, 0)
            self.drawGrowingAreaContour()

        pass

    def regionModMouseReleasedEvent(self, Event):
        if Event.buttons() == Qt.RightButton:
            print('Right button released')
        pass
#==================================================================================================

#=====================================Region mod mouse move event==================================
    def regionModMouseMoveEvent(self, event):
        self.posX = event.pos().x()
        self.posY = event.pos().y()
        if event.buttons() == Qt.LeftButton and self.regionDrawMod == 0:
            if self.regionDrawMod == 0:
                xAxis = event.pos().x()
                yAxis = event.pos().y()
                if xAxis >= 0 and yAxis >= 0:
                    self.PosXY[0] = math.floor(xAxis * (self.baseImageSize / self.imLable.width()))
                    self.PosXY[1] = math.floor(yAxis * (self.baseImageSize / self.imLable.height()))
                    self.seedList[self.seedSelectNum] = (self.PosXY[0], self.PosXY[1])
                else:
                    print('Region Mod has Nagtive number')
        elif event.buttons() == Qt.LeftButton and self.regionDrawMod != 0:
            xAxis = event.pos().x()
            yAxis = event.pos().y()
            if xAxis >= 0 and yAxis >= 0:
                tmpX = math.floor(xAxis * (self.baseImageSize / self.imLable.width()))
                tmpY = math.floor(yAxis * (self.baseImageSize / self.imLable.height()))
                if self.regionDrawMod == 1:
                    self.regionDrawLayerEvent(tmpX, tmpY, 1)
                elif self.regionDrawMod == 2:
                    self.regionDrawLayerEvent(tmpX, tmpY, 0)
                else:
                    print('regionModMouseMoveEvent regionDrawMod error......')
                    return
            self.drawGrowingAreaContour()
            return
        else:
            print('regionModMouseMoveEvent error......')
        self.choiceDisplayMod()
        pass

#=================================SetWindowSizeEvent==========================================
    def setScaleSize(self, maxnum, minnum):
        self.faceWindowH = maxnum
        self.faceWindowV = minnum * (max(self.xSpacing, self.ySpacing, self.zSpacing) / min(self.xSpacing, self.ySpacing, self.zSpacing))
        pass

    def getResizeEvent(self, sizeX, sizeY):
        if self.currentFace == self.facePlane[0]:
            tmpSize = min(sizeX, sizeY)
            self.imLable.resize(tmpSize, tmpSize)

        elif self.currentFace == self.facePlane[1]:
            #==================Resize Lable===================
            self.setScaleSize(min(sizeX, sizeY), min(sizeX, sizeY) * (min(self.datas.shape)/max(self.datas.shape)))
            self.imLable.resize(self.faceWindowH, self.faceWindowV)

        elif self.currentFace == self.facePlane[2]:
            self.setScaleSize(min(sizeX, sizeY), min(sizeX, sizeY) * (min(self.datas.shape) / max(self.datas.shape)))
            self.imLable.resize(self.faceWindowH, self.faceWindowV)

        #==================Move Lable=====================
        maxPosY = max(sizeY, self.imLable.height())
        minPoxY = min(sizeY, self.imLable.height())
        tmpPosX = np.clip((sizeX - sizeY), 0, max(sizeX, sizeY)) / 2
        tmpPosY = (maxPosY - minPoxY) / 2
        self.imLable.move(tmpPosX, tmpPosY)
        pass


#===========================mousewheelEvent==================================
    def regionGrowingWheelEvent(self, event):
        angle = event.angleDelta() / 8
        angleX = angle.x()
        angleY = angle.y()

        if angleY > 0:
            self.regionDrawSize -= 1
        elif angleY < 0:
            self.regionDrawSize += 1
        pass

#==========================RegionDrawMod=====================
    def setRegionDrawMod(self, event):
        if event == 0:
            self.regionDrawMod = 0
        elif event == 1:
            self.regionDrawMod = 1
        elif event == 2:
            self.regionDrawMod = 2
        else:
            print('setRegionDrawMod error....')
        pass

#====================Use for paint or eraser====================
    def paintEvent(self, QPaintEvent):
        pen1 = QPen(Qt.blue, 1)
        q = QPainter(self)
        q.setPen(pen1)
        q.drawRect(self.posX - 25, self.posY - 25, 50, 50)
        # print('paintEvent')
        pass


    @property
    def window_width(self):
        return self._high_hu - self._low_hu





#=======================================================================================================================
# pathDicom = "D:/Dicomfile/MT_07/"
# idxSlice = 50
# reader = SimpleITK.ImageSeriesReader()
# filenamesDICOM = reader.GetGDCMSeriesFileNames(pathDicom)
#
# reader.SetFileNames(filenamesDICOM)
# imgOriginals = reader.Execute()
# datas = SimpleITK.GetArrayFromImage(imgOriginals)
# Spacing = imgOriginals.GetSpacing()
#
# if __name__ == '__main__':
#     app = QApplication(sys.argv)
#     win = dicomImage2DdisplayWidget(face=0, datas= datas, spacing=Spacing)
#     win.show()
#     sys.exit(app.exec_())
コード例 #10
0
ファイル: E5SideBar.py プロジェクト: zhoumaomao11/Pymakr
class E5SideBar(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)
        """
        super(E5SideBar, self).__init__(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.tr("Deselect to activate automatic collapsing"))
        self.barLayout = QBoxLayout(QBoxLayout.LeftToRight)
        self.barLayout.setContentsMargins(0, 0, 0, 0)
        self.layout = QBoxLayout(QBoxLayout.TopToBottom)
        self.layout.setContentsMargins(0, 0, 0, 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.__delayTimer.timeout.connect(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 = E5SideBar.North
        if orientation is None:
            orientation = E5SideBar.North
        self.setOrientation(orientation)

        self.__tabBar.currentChanged[int].connect(
            self.__stackedWidget.setCurrentIndex)
        e5App().focusChanged.connect(self.__appFocusChanged)
        self.__autoHideButton.toggled[bool].connect(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.splitter.splitterMoved.connect(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 [E5SideBar.North, E5SideBar.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 [E5SideBar.North, E5SideBar.South]:
            self.setFixedHeight(self.__tabBar.minimumSizeHint().height())
        else:
            self.setFixedWidth(self.__tabBar.minimumSizeHint().width())

        self.__actionMethod = None

    def expand(self):
        """
        Public method to record a expand request.
        """
        self.__delayTimer.stop()
        self.__actionMethod = self.__expandIt
        self.__delayTimer.start()

    def __expandIt(self):
        """
        Private method to expand the sidebar.
        """
        self.__minimized = False
        self.__stackedWidget.show()
        self.resize(self.__bigSize)
        if self.__orientation in [E5SideBar.North, E5SideBar.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):
        """
        Public 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:
                if qVersion() >= "5.0.0":
                    delta = evt.angleDelta().y()
                else:
                    delta = evt.delta()
                if 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 label text of the tab
            (QIcon, string)
        @param label the labeltext of the tab (string) (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 [E5SideBar.North, E5SideBar.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)
        @param label the labeltext of the tab (string) (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 [E5SideBar.North, E5SideBar.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 [E5SideBar.North, E5SideBar.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 == E5SideBar.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 == E5SideBar.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 == E5SideBar.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 == E5SideBar.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 (string)
        """
        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 (string)
        """
        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 (string)
        """
        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 tip tooltip text to set (string)
        """
        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 (string)
        """
        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 text WhatsThis text to set (string)
        """
        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 [E5SideBar.North, E5SideBar.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.setVersion(QDataStream.Qt_4_6)

        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 [E5SideBar.North, E5SideBar.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.setVersion(QDataStream.Qt_4_6)
        stream.readUInt16()  # version
        minimized = stream.readBool()

        if minimized and not self.__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.
        """
        e5App().focusChanged.disconnect(self.__appFocusChanged)
コード例 #11
0
    def load_settings_widgets_from_pipeline_groupbox(self, position):
        """
        Extracts all widgets from a single algorithm and returns a QBoxLayout
        Args:
            alg: the alg instance we extract from

        Returns: a QBoxLayout containing all widgets for this particular alg.

        """

        alg = self.pipeline.executed_cats[position].active_algorithm

        print("alg " + str(alg))
        print("cat " + str(self.pipeline.executed_cats[position]))

        empty_flag = True

        groupOfSliders = QGroupBox()
        sp = QSizePolicy()
        sp.setVerticalPolicy(QSizePolicy.Preferred)
        # groupOfSliders.setSizePolicy(sp)
        groupOfSliderssLayout = QBoxLayout(QBoxLayout.TopToBottom)
        groupOfSliderssLayout.setContentsMargins(0, -0, -0, 0)
        groupOfSliderssLayout.setAlignment(Qt.AlignTop)
        groupOfSliderssLayout.setSpacing(0)

        print("Build Slider @ "+ str(position))

        # create integer sliders
        for slider in alg.integer_sliders:
            empty_flag = False
            print("slider.value " + str(slider.value))
            print("slider " + str(slider))
            #print(alg.get_name() + ": add slider (int).")
            groupOfSliderssLayout.addWidget(
                SliderWidget(slider.name, slider.lower, slider.upper, slider.step_size, slider.value,
                             slider.set_value, False))

        # create float sliders
        for slider in alg.float_sliders:
            empty_flag = False
            #print(alg.get_name() + ": add slider (float).")
            groupOfSliderssLayout.addWidget(
                SliderWidget(slider.name, slider.lower, slider.upper, slider.step_size, slider.value,
                             slider.set_value, True), 0, Qt.AlignTop)

        # create checkboxes
        for checkbox in alg.checkboxes:
            empty_flag = False
            #print(alg.get_name() + ": add checkbox.")
            groupOfSliderssLayout.addWidget(CheckBoxWidget(checkbox.name, checkbox.value, checkbox.set_value), 0,
                                            Qt.AlignTop)

        # create dropdowns
        for combobox in alg.drop_downs:
            empty_flag = False
            #print(alg.get_name() + ": add combobox.")
            groupOfSliderssLayout.addWidget(
                ComboBoxWidget(combobox.name, combobox.options, combobox.set_value, combobox.value), 0, Qt.AlignTop)

        if empty_flag:
            label = QLabel()
            label.setText("This algorithm has no Settings.")
            groupOfSliderssLayout.addWidget(label, 0, Qt.AlignHCenter)

        groupOfSliders.setLayout(groupOfSliderssLayout)

        return groupOfSliders
コード例 #12
0
ファイル: E5SideBar.py プロジェクト: pycom/EricShort
class E5SideBar(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)
        """
        super(E5SideBar, self).__init__(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.tr("Deselect to activate automatic collapsing"))
        self.barLayout = QBoxLayout(QBoxLayout.LeftToRight)
        self.barLayout.setContentsMargins(0, 0, 0, 0)
        self.layout = QBoxLayout(QBoxLayout.TopToBottom)
        self.layout.setContentsMargins(0, 0, 0, 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.__delayTimer.timeout.connect(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 = E5SideBar.North
        if orientation is None:
            orientation = E5SideBar.North
        self.setOrientation(orientation)
        
        self.__tabBar.currentChanged[int].connect(
            self.__stackedWidget.setCurrentIndex)
        e5App().focusChanged[QWidget, QWidget].connect(self.__appFocusChanged)
        self.__autoHideButton.toggled[bool].connect(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.splitter.splitterMoved.connect(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 [E5SideBar.North, E5SideBar.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 [E5SideBar.North, E5SideBar.South]:
            self.setFixedHeight(self.__tabBar.minimumSizeHint().height())
        else:
            self.setFixedWidth(self.__tabBar.minimumSizeHint().width())
        
        self.__actionMethod = None
    
    def expand(self):
        """
        Public method to record a expand request.
        """
        self.__delayTimer.stop()
        self.__actionMethod = self.__expandIt
        self.__delayTimer.start()
    
    def __expandIt(self):
        """
        Private method to expand the sidebar.
        """
        self.__minimized = False
        self.__stackedWidget.show()
        self.resize(self.__bigSize)
        if self.__orientation in [E5SideBar.North, E5SideBar.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):
        """
        Public 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:
                if qVersion() >= "5.0.0":
                    delta = evt.angleDelta().y()
                else:
                    delta = evt.delta()
                if 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 label text of the tab
            (QIcon, string)
        @param label the labeltext of the tab (string) (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 [E5SideBar.North, E5SideBar.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)
        @param label the labeltext of the tab (string) (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 [E5SideBar.North, E5SideBar.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 [E5SideBar.North, E5SideBar.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 == E5SideBar.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 == E5SideBar.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 == E5SideBar.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 == E5SideBar.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 (string)
        """
        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 (string)
        """
        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 (string)
        """
        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 tip tooltip text to set (string)
        """
        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 (string)
        """
        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 text WhatsThis text to set (string)
        """
        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 [E5SideBar.North, E5SideBar.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.setVersion(QDataStream.Qt_4_6)
        
        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 [E5SideBar.North, E5SideBar.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.setVersion(QDataStream.Qt_4_6)
        stream.readUInt16()  # version
        minimized = stream.readBool()
        
        if minimized and not self.__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.
        """
        e5App().focusChanged[QWidget, QWidget].disconnect(
            self.__appFocusChanged)
コード例 #13
0
class SegmentListItem(QFrame):
    def __init__(self, store, segment, is_selected, set_segment_end_frame_cb, clicked_cb, delete_cb):
        QFrame.__init__(self)
        self.segment = segment
        self.store = store
        self.set_segment_end_frame_cb = set_segment_end_frame_cb
        self.clicked_cb = clicked_cb
        self.start_frame = segment.start_frame
        self.end_frame = segment.end_frame
        self.is_selected = is_selected
        self.delete_cb = delete_cb
        self._init_ui()

    def mousePressEvent(self, event):
        self.clicked_cb(self.segment.id)
        QFrame.mousePressEvent(self, event)

    def _handle_set_end_frame(self):
        self.set_segment_end_frame_cb(self.segment.id)

    def _handle_delete(self):
        self.delete_cb(self.segment.id)

    def _on_label_click(self, text):
        self.store.set_video_frame(int(text))


    def _init_ui(self):
        self.layout = QBoxLayout(QBoxLayout.TopToBottom)
        self.frames_layout = QHBoxLayout()
        self.tags_layout = QHBoxLayout()
        self.tags_layout.setSpacing(0)
        self.tags_layout.setContentsMargins(0,0,0,0)

        self.start_frame_label = PressableLabel(str(self.start_frame), False, self._on_label_click)
        self.frame_separator = PressableLabel("-")
        self.frame_separator.setDisabled(True)

        self.end_container = QBoxLayout(QBoxLayout.LeftToRight)
        if not self.end_frame:
            self.end_button = QPushButton('End')
            self.end_container.setAlignment(Qt.AlignRight)
            self.end_container.addWidget(self.end_button)
            self.end_button.clicked.connect(self._handle_set_end_frame)
        else:
            self.end_widget = PressableLabel(str(self.end_frame), False, self._on_label_click)
            self.end_container.addWidget(self.end_widget)

        self.frames_layout.setSpacing(0)

        self.frames_layout.addWidget(self.start_frame_label)
        self.frames_layout.addWidget(self.frame_separator)

        if not self.end_frame:
            self.frames_layout.addStretch()

        self.frames_layout.addLayout(self.end_container)
        self.delete_cont = QBoxLayout(QBoxLayout.TopToBottom)
        self.delete = QPushButton('Del')
        self.delete_cont.addWidget(self.delete)
        self.delete_cont.setAlignment(Qt.AlignRight)
        self.frames_layout.addLayout(self.delete_cont)
        self.delete.clicked.connect(self._handle_delete)

        self.tags_layout.addWidget(PressableLabel('', True))
        for tag in self.segment.tags:
            self.tags_layout.addWidget(PressableLabel(tag.name, True))
        self.tags_layout.addStretch()

        self.layout.setContentsMargins(0,0,0,0)
        self.layout.addLayout(self.frames_layout)
        self.setLayout(self.layout)
        self.layout.addLayout(self.tags_layout)

        if self.is_selected:
            self.setProperty('class', 'selected')

        self._init_style()

    def _init_style(self):
        file = QFile(Registry.SEGMENT_LIST_ITEM_QSS);
        file.open(QFile.ReadOnly);
        styleSheet = file.readAll().data();
        self.setStyleSheet(styleSheet.decode("utf-8"));
コード例 #14
0
    def __init__(self, parent):
        super(NewsWindow, self).__init__(parent)
        self.parent = parent
        # top table - news list and filters
        self.table = QTableWidget(0, 5)
        horizLabels = ["", "", "", "", ""]
        self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table.setSelectionMode(QAbstractItemView.SingleSelection)
        self.table.itemSelectionChanged.connect(self.doDisplayNewsHeadline)
        self.table.setHorizontalHeaderLabels(horizLabels)
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.table.setWordWrap(True)
        self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)
        topLayout = QGridLayout()
        topLayout.addWidget(self.table, 0, 1)
        filterLayout = QBoxLayout(QBoxLayout.TopToBottom)
        self.filters = [
            QPushButton(parent.graphics.icon[23 + i], "") for i in range(5)
        ]
        filterGroup = QButtonGroup()
        for i, j in zip(self.filters, range(5)):
            i.setFixedSize(120, 32)
            i.setAutoExclusive(True)
            i.setCheckable(True)
            i.released.connect(partial(self.doRefreshNews, j))
            filterGroup.addButton(i)
            filterLayout.addWidget(i)
            filterLayout.addSpacing(-5)
        filterLayout.addSpacing(30)
        filterLayout.setAlignment(Qt.AlignVCenter)
        self.ctryList = QComboBox()
        self.ctryList.setMaxVisibleItems(10)
        self.ctryList.addItems([
            Local.strings[Local.DATA_COUNTRIES + i][Local.CTRY_NAME]
            for i in range(80)
        ])
        self.ctryList.currentIndexChanged.connect(
            partial(self.doRefreshNews, 5))
        self.localNews = QRadioButton()
        self.localNews.released.connect(partial(self.doRefreshNews, 5))
        filterGroup.addButton(self.localNews)
        filterLayout.addWidget(self.localNews)
        filterLayout.addWidget(self.ctryList)
        topLayout.addLayout(filterLayout, 0, 0)
        topLayout.setContentsMargins(-50, 0, 0, 0)
        self.table.setFixedHeight(220)

        # left half - news
        buttons = QBoxLayout(QBoxLayout.LeftToRight)
        leftLayout = QBoxLayout(QBoxLayout.TopToBottom)
        leftLayout.setContentsMargins(-80, 0, 0, 0)
        self.newsHline = QLabel()
        self.newsHline.setWordWrap(True)
        self.newsHline.setFixedHeight(40)
        leftLayout.addSpacing(25)
        leftLayout.addWidget(self.newsHline)
        leftLayout.addSpacing(30)
        self.question = QPushButton()
        self.backDown = QPushButton()
        self.question.released.connect(self.doTough)
        self.backDown.released.connect(self.doLoose)
        for i in (self.question, self.backDown):
            buttons.addWidget(i)
        leftLayout.addLayout(buttons)
        self.reactionLine = QLabel()
        self.reactionLine.setFixedHeight(30)
        self.reactionLine.setWordWrap(True)
        leftLayout.addSpacing(20)
        leftLayout.addWidget(self.reactionLine)
        leftLayout.addSpacing(20)
        leftInfoLayout = [QBoxLayout(QBoxLayout.LeftToRight) for i in range(3)]
        self.leftInfo = [QLabel() for i in range(3)]
        self.leftInfoVal = [QLabel() for i in range(3)]
        for i in range(3):
            leftInfoLayout[i].addWidget(self.leftInfo[i])
            leftInfoLayout[i].addWidget(self.leftInfoVal[i])
            leftLayout.addLayout(leftInfoLayout[i])
            if i < 2: leftLayout.addSpacing(-5)

        # right half - advisory
        rightLayout = QBoxLayout(QBoxLayout.TopToBottom)
        rightLayout.setContentsMargins(0, -50, 0, 0)
        #rightLayout.addWidget(self.advisory)
        headsLayout = QBoxLayout(QBoxLayout.LeftToRight)
        headsColumn = [QBoxLayout(QBoxLayout.TopToBottom) for i in range(2)]
        head = [QBoxLayout(QBoxLayout.LeftToRight) for i in range(4)]
        self.picture = [QLabel() for i in range(4)]
        self.advice = [QLabel() for i in range(4)]
        for i in range(4):
            self.picture[i].setPixmap(parent.graphics.advisor[i])
            self.advice[i].setWordWrap(True)
            self.advice[i].setFixedWidth(100)
            head[i].addWidget(self.picture[i])
            head[i].addWidget(self.advice[i])
            headsColumn[i // 2].addLayout(head[i])
        self.closeUpButton = QPushButton()

        for i in range(2):
            headsLayout.addLayout(headsColumn[i])
        rightLayout.addLayout(headsLayout)

        # save right and left layouts into groups
        self.detailGroup = [QGroupBox() for i in range(3)]
        self.detailGroup[0].setLayout(leftLayout)
        self.detailGroup[1].setLayout(rightLayout)
        self.detailGroup[2].setLayout(topLayout)

        mainLayout = QGridLayout()
        mainLayout.addWidget(self.detailGroup[2], 0, 0, 1, 2)
        for i in range(2):
            mainLayout.addWidget(self.detailGroup[i], 1, i)

        self.setStrings()
        self.setLayout(mainLayout)
        self.setFixedSize(830, 590)
        self.setModal(True)
コード例 #15
0
    def initUI(self):
        boxlayout = QBoxLayout(QBoxLayout.TopToBottom)
        self.setLayout(boxlayout)

        lblWelcome = QLabel('Welcome to the earthquake simulation system')
        lblWelcome.setFont(gui.QFont("Verdana", 14))
        lblSubtitle = QLabel('Upload your .smc files here')
        lblSubtitle.setFont(gui.QFont("Verdana", 10))

        canvas = Canvas(self, width=10, height=10)

        path = QDir.rootPath()

        treeview = QTreeView()
        listview = QListView()

        dirModel = QFileSystemModel()
        dirModel.setFilter(QDir.NoDotAndDotDot | QDir.AllDirs)
        treeview.setModel(dirModel)

        fileModel = QFileSystemModel()
        fileModel.setFilter(QDir.NoDotAndDotDot | QDir.Files)
        listview.setModel(fileModel)

        treeview.setRootIndex(dirModel.index(path))
        listview.setRootIndex(fileModel.index(path))

        btnUpload = QPushButton('Upload files')
        btnUpload.setFixedSize(100, 40)
        btnUpload.setFont(gui.QFont("Verdana", 10))
        btnUpload.clicked.connect(self.openFileChooser)

        btnSimulate = QPushButton('Simulate')
        btnSimulate.setFixedSize(100, 40)
        btnSimulate.setFont(gui.QFont("Verdana", 10))
        btnSimulate.clicked.connect(self.simulate)

        hbox_FileChooser = QHBoxLayout()
        hbox_FileChooser.addWidget(btnUpload)
        hbox_FileChooser.addWidget(self.lblFileName)

        vbox_treeViews = QVBoxLayout()
        vbox_treeViews.addWidget(treeview)
        vbox_treeViews.addWidget(listview)

        hbox_Graphics = QHBoxLayout()
        hbox_Graphics.addLayout(vbox_treeViews)
        hbox_Graphics.addWidget(canvas)

        boxlayout.addWidget(lblWelcome, 0, cor.Qt.AlignCenter)
        boxlayout.addWidget(lblSubtitle, 0, cor.Qt.AlignCenter)

        boxlayout.addLayout(hbox_FileChooser, 0)
        boxlayout.addWidget(btnSimulate, 0, cor.Qt.AlignCenter)
        boxlayout.setAlignment(cor.Qt.AlignCenter)
        boxlayout.setSpacing(20)
        boxlayout.addLayout(hbox_Graphics, 0)

        btnUpload = QPushButton('Upload files')
        btnUpload.setFixedSize(100, 40)
        btnUpload.setFont(gui.QFont("Verdana", 10))
        btnUpload.clicked.connect(self.openFileChooser)

        self.resize(800, 500)
        self.setWindowTitle('Earthquake Simulator')
        self.show()