当前位置: 首页>>代码示例>>Python>>正文


Python QGraphicsScene.sceneRect方法代码示例

本文整理汇总了Python中PyQt5.QtWidgets.QGraphicsScene.sceneRect方法的典型用法代码示例。如果您正苦于以下问题:Python QGraphicsScene.sceneRect方法的具体用法?Python QGraphicsScene.sceneRect怎么用?Python QGraphicsScene.sceneRect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在PyQt5.QtWidgets.QGraphicsScene的用法示例。


在下文中一共展示了QGraphicsScene.sceneRect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: go

# 需要导入模块: from PyQt5.QtWidgets import QGraphicsScene [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsScene import sceneRect [as 别名]
def go():
    global graphic_view, status_label
    data_parent, data_child = Pipe(duplex=False)
    receiver = Process(target=generate_data, args=(data_child,))
    receiver.daemon = True
    receiver.start()

    scene = QGraphicsScene()
    graphic_view.setScene(scene)
    scene.setSceneRect(0, 0, 1024, 1024)

    x_pos = 0
    y_pos = 0
    t = time.time()
    while True:
        speed = time.time()
        data = data_parent.recv()
        spectrogram = Spectrogram(data)
        pixmap = QPixmap.fromImage(spectrogram.create_spectrogram_image(transpose=True))

        scene.setSceneRect(scene.sceneRect().adjusted(0, 0, 0, pixmap.height()))
        item = scene.addPixmap(pixmap)
        item.setPos(x_pos, y_pos)
        y_pos += pixmap.height()
        graphic_view.fitInView(scene.sceneRect())
        status_label.setText("Height: {0:.0f} // Speed: {1:.2f}  // Total Time: {2:.2f}".format(scene.sceneRect().height(),
                                                                                                1/(time.time()-speed),
                                                                                                time.time()-t))
        QApplication.instance().processEvents()
开发者ID:jopohl,项目名称:urh,代码行数:31,代码来源:live_spectrogram.py

示例2: MainWindow

# 需要导入模块: from PyQt5.QtWidgets import QGraphicsScene [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsScene import sceneRect [as 别名]
class MainWindow(QMainWindow):

    #somewhere in constructor:
    def __init__(self):
        super(MainWindow, self).__init__()
        uic.loadUi('ui_window.ui', self)
        self.setupUI()

    def setupUI(self):
        root = QFileInfo(__file__).absolutePath()
        self.actionOpen.setIcon(QIcon(root+'/images/Live Mail.ico'))
        self.actionSave.setIcon(QIcon(root+'/images/489751-Floppy_Disk-128.png'))
        self.actionSelect.setIcon(QIcon(root+'/images/mouse.png'))
        self.actionRip_off.setIcon(QIcon(root+'/images/rip_off.png'))
        self.setWindowTitle('AnimDNA')
        self.actionAnalyze_structure.setIcon(QIcon(root+'/images/transformation.png'))
        self.setWindowIcon((QIcon(root+'/images/bug.png')))
        from PyQt5 import QtCore, QtGui, QtWidgets
        self.main_splitter = QtWidgets.QSplitter(self.centralwidget)
        self.path_splitter = QtWidgets.QSplitter(self.main_splitter)
        self.renderView = CustomQGraphicsView(self.path_splitter)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.renderView.sizePolicy().hasHeightForWidth())
        self.renderView.setSizePolicy(sizePolicy)
        self.renderView.setMinimumSize(QtCore.QSize(0, 0))
        self.renderView.setMouseTracking(True)
        self.renderView.setFocusPolicy(QtCore.Qt.WheelFocus)
        self.renderView.setFrameShadow(QtWidgets.QFrame.Plain)
        self.renderView.setLineWidth(0)
        self.renderView.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.renderView.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.renderView.setRenderHints(QtGui.QPainter.Antialiasing|QtGui.QPainter.HighQualityAntialiasing|QtGui.QPainter.TextAntialiasing)
        self.renderView.setTransformationAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse)
        self.renderView.setObjectName("renderView")
        self.renderView.setupGL(self)
        self.gridLayout.addWidget(self.main_splitter, 0, 0, 1, 1)
        self.action_modify = QtWidgets.QAction(self)
        self.action_modify.setCheckable(True)



    def updateRenderView(self,doc_ctrl):
         doc = doc_ctrl._document
         self.pathscene = QGraphicsScene(parent=self.renderView)
         self.pathroot = PathRootItem(rect=self.pathscene.sceneRect(),\
                                     parent=None,\
                                     window=self,\
                                     document= doc_ctrl._document)
         self.pathroot.setFlag(QGraphicsItem.ItemHasNoContents)
         self.pathscene.addItem(self.pathroot)
         self.pathscene.setItemIndexMethod(QGraphicsScene.NoIndex)
         assert self.pathroot.scene() == self.pathscene
         self.renderView.setScene(self.pathscene)
         self.renderView.scene_root_item = self.pathroot
         self.renderView._scale_fit_factor = 0.9
         self.renderView._name = 'renderView'
         self.path_tool_manager = PathToolManager(self,self.path_toolbar)
开发者ID:amylittleyang,项目名称:OtraCAD,代码行数:61,代码来源:ui_window.py

示例3: main

# 需要导入模块: from PyQt5.QtWidgets import QGraphicsScene [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsScene import sceneRect [as 别名]
def main():

    app = QApplication(sys.argv)

    grview = QGraphicsView()
    scene = QGraphicsScene()
    scene.setSceneRect(0, 0, 680, 459)

    scene.addPixmap(QPixmap('../images/phototest.tif'))
    grview.setScene(scene)

    item = AreaItem(0, 0, 300, 150)
    item.areaColor = QColor(155, 155, 0, 75)
    scene.addItem(item)

    grview.fitInView(scene.sceneRect(), Qt.KeepAspectRatio)
    grview.show()
    sys.exit(app.exec_())
开发者ID:zdenop,项目名称:pyTesseractDemo,代码行数:20,代码来源:areaitem.py

示例4: MainWindow

# 需要导入模块: from PyQt5.QtWidgets import QGraphicsScene [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsScene import sceneRect [as 别名]

#.........这里部分代码省略.........
    def set_img_list(self, dirname):
        """Create a list of readable images from the current directory."""
        filelist = os.listdir(dirname)
        self.filelist = [os.path.join(dirname, fname) for fname in filelist
                        if fname.lower().endswith(self.read_list)]
        self.filelist.sort()
        self.last_file = len(self.filelist) - 1

    def get_img(self):
        """Get image from fname and create pixmap."""
        image = QImage(self.fname)
        self.pixmap = QPixmap.fromImage(image)
        self.setWindowTitle(self.fname.rsplit('/', 1)[1])

    def reload_auto(self):
        """Load a new image with auto-orientation."""
        self.get_img()
        try:
            orient = GExiv2.Metadata(self.fname)['Exif.Image.Orientation']
            self.orient_dict[orient]()
        except:
            self.load_img()

    def reload_nonauto(self):
        """Load a new image without auto-orientation."""
        self.get_img()
        self.load_img()

    def load_img_fit(self):
        """Load the image to fit the window."""
        self.scene.clear()
        self.scene.addPixmap(self.pixmap)
        self.scene.setSceneRect(0, 0, self.pixmap.width(), self.pixmap.height())
        self.img_view.fitInView(self.scene.sceneRect(), Qt.KeepAspectRatio)

    def load_img_1to1(self):
        """Load the image at its original size."""
        self.scene.clear()
        self.img_view.resetTransform()
        self.scene.addPixmap(self.pixmap)
        self.scene.setSceneRect(0, 0, self.pixmap.width(), self.pixmap.height())
        pixitem = QGraphicsPixmapItem(self.pixmap)
        self.img_view.centerOn(pixitem)

    def go_next_img(self):
        self.img_index = self.img_index + 1 if self.img_index < self.last_file else 0
        self.fname = self.filelist[self.img_index]
        self.reload_img()

    def go_prev_img(self):
        self.img_index = self.img_index - 1 if self.img_index else self.last_file
        self.fname = self.filelist[self.img_index]
        self.reload_img()

    def zoom_default(self):
        """Toggle best fit / original size loading."""
        if self.fit_win_act.isChecked():
            self.load_img = self.load_img_fit
            self.create_dict()
            self.load_img()
        else:
            self.load_img = self.load_img_1to1
            self.create_dict()
            self.load_img()

    def img_rotate(self, angle):
开发者ID:riverrun,项目名称:cheesemaker,代码行数:70,代码来源:gui.py

示例5: MapCanvas

# 需要导入模块: from PyQt5.QtWidgets import QGraphicsScene [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsScene import sceneRect [as 别名]

#.........这里部分代码省略.........
        for i, rect in enumerate(self.map_points_items):
            rect.setRect(
                self.map_data.map_points[i].x,
                self.map_data.map_points[i].y,
                max(5, 5 / self.scale_ratio),
                max(5, 5 / self.scale_ratio)
            )

        # Scale map point's text
        for i, text in enumerate(self.map_points_text_items):
            text.setFont(
                QFont(
                    'Times New Roman',
                    max(8, 8 / self.scale_ratio)
                )
            )
            text.setX(
                self.map_data.map_points[i].x + max(5, 5 / self.scale_ratio)
            )

        # Scale player point
        circle_size = max(10, 10 / self.scale_ratio)
        for player in self.map_points_player_items.keys():
            self.map_points_player_items[player].setRect(
                self.players[player].x - circle_size / 2,
                self.players[player].y - circle_size / 2,
                circle_size,
                circle_size
            )

    def set_scene_padding(self, padding_x, padding_y):
        # Make it so that if you are zoomed out, you can still
        # drag the map around (not that smooth)
        rect = self._scene.sceneRect()
        rect.adjust(
            -padding_x * 2, -padding_y * 2, padding_x * 2, padding_y * 2
        )
        self.setSceneRect(rect)

    def draw_loading_screen(self):
        pass

    def fit_to_window(self):
        pass

    def center(self):
        if self.settings.get_value('maps', 'center_on') == 'player':
            # Center on Player for now by default
            # Added try/except because initialization causes resize event
            try:
                if '__you__' in self.players.keys():
                    self.centerOn(
                        self.players['__you__'].x,
                        self.players['__you__'].y
                    )
            except AttributeError as e:
                print("MapCanvas().center():", e)

    def add_player(self, name, time_stamp, location):
        y, x, z = [float(value) for value in location.strip().split(',')]
        y = -y
        x = -x
        if name not in self.players.keys():
            r, g, b = (0, 255, 0)
            flag = '__other__'
            user_level = None
开发者ID:nomns,项目名称:Parse99,代码行数:70,代码来源:mapcanvas.py

示例6: Ui_MainWindow

# 需要导入模块: from PyQt5.QtWidgets import QGraphicsScene [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsScene import sceneRect [as 别名]

#.........这里部分代码省略.........

    def overlayFrameNoSpinBoxValueChanged(self, i):
        if self.trackingPathGroup is not None:
            self.trackingPathGroup.setOverlayFrameNo(i)
        self.updateInputGraphicsView()

    def stackedWidgetCurrentChanged(self, i):
        currentWidget = self.stackedWidget.currentWidget()

        currentWidget.estimator_init()
        self.algorithmSettingsGroupBox.setTitle(currentWidget.get_name())
        self.resetDataframe()

    def updateInputGraphicsView(self):
        if self.inputPixmapItem is not None:
            self.inputScene.removeItem(self.inputPixmapItem)

        if self.filter is not None and hasattr(self.filter, "resize_flag") and self.filter.resize_flag:
            qimg = misc.cvMatToQImage(cv2.pyrDown(self.cv_img))
        else:
            qimg = misc.cvMatToQImage(self.cv_img)

        pixmap = QPixmap.fromImage(qimg)

        self.inputPixmapItem = QGraphicsPixmapItem(pixmap)
        rect = QtCore.QRectF(pixmap.rect())
        self.inputScene.setSceneRect(rect)
        self.inputScene.addItem(self.inputPixmapItem)

        self.inputGraphicsView.viewport().update()
        self.inputGraphicsViewResized()

    def inputGraphicsViewResized(self, event=None):
        self.inputGraphicsView.fitInView(self.inputScene.sceneRect(), QtCore.Qt.KeepAspectRatio)

    def updatePath(self):
        try:
            attrs = self.stackedWidget.currentWidget().get_attributes()
            attrs.keys()
        except Exception as e:
            msg = 'Tracking Lib. Attributes Error:\n{}'.format(e)
            self.generateCriticalMessage(msg)
            return

        if 'position' in attrs:
            self.trackingPathGroup.setPoints(self.currentFrameNo)

        if 'arrow' in attrs:
            for i, arrow_item in enumerate(self.item_dict['arrow']):
                begin = self.df['position'].loc[self.currentFrameNo, i].as_matrix()
                end = self.df['arrow'].loc[self.currentFrameNo, i].as_matrix()
                arrow_item.setPosition(begin, end)

        if 'path' in attrs:
            for path_item, path_data in zip(self.item_dict['path'], self.data_dict['path'][self.currentFrameNo]):
                poly = QPolygonF()
                for p in path_data:
                    poly.append(QPointF(*p))

                painter_path = QPainterPath()
                painter_path.addPolygon(poly)
                path_item.setPath(painter_path)

                pen = QPen(Qt.blue)
                pen.setWidth(2)
                path_item.setPen(pen)
开发者ID:Licht-T,项目名称:UMATracker-Detect-Center,代码行数:70,代码来源:main.py

示例7: QGraphicsScene

# 需要导入模块: from PyQt5.QtWidgets import QGraphicsScene [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsScene import sceneRect [as 别名]
    w = textItem.boundingRect().width()
    stickManBoundingRect = stickMan.mapToScene(stickMan.boundingRect()).boundingRect()
    textItem.setPos(-w / 2.0, stickManBoundingRect.bottom() + 25.0)

    scene = QGraphicsScene()
    scene.addItem(stickMan)
    scene.addItem(textItem)
    scene.setBackgroundBrush(Qt.black)

    view = GraphicsView()
    view.setRenderHints(QPainter.Antialiasing)
    view.setTransformationAnchor(QGraphicsView.NoAnchor)
    view.setScene(scene)
    view.show()
    view.setFocus()

    # Make enough room in the scene for stickman to jump and die.
    sceneRect = scene.sceneRect()
    view.resize(sceneRect.width() + 100, sceneRect.height() + 100)
    view.setSceneRect(sceneRect)

    cycle = LifeCycle(stickMan, view)
    cycle.setDeathAnimation(":/animations/dead")

    cycle.addActivity(":/animations/jumping", Qt.Key_J)
    cycle.addActivity(":/animations/dancing", Qt.Key_D)
    cycle.addActivity(":/animations/chilling", Qt.Key_C)
    cycle.start()

    sys.exit(app.exec_())
开发者ID:Magdno1,项目名称:Arianrhod,代码行数:32,代码来源:stickman.py

示例8: Ui_MainWindow

# 需要导入模块: from PyQt5.QtWidgets import QGraphicsScene [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsScene import sceneRect [as 别名]
class Ui_MainWindow(QtWidgets.QMainWindow, Ui_MainWindowBase):
    def __init__(self):
        super(Ui_MainWindow, self).__init__()
        self.setupUi(self)

        self.videoPlaybackInit()
        self.imgInit()
        self.menuInit()

        self.df = None
        self.trackingPathGroup = None
        self.drawingFlag = False
        self.handInputSystem = None
        self.handInputSystem = HandInputSystem()
        self.handInputSystem.setRect(self.inputScene.sceneRect())
        self.inputScene.addItem(self.handInputSystem)
        self.handInputSystem.addNewDataFrame()
        self.currentFrameNo = 0
            
        self.colors = []

        self.circleCheckBox.stateChanged.connect(self.polyLineCheckBoxStateChanged)
        self.lineCheckBox.stateChanged.connect(self.polyLineCheckBoxStateChanged)
        self.overlayCheckBox.stateChanged.connect(self.overlayCheckBoxStateChanged)
        self.radiusSpinBox.valueChanged.connect(self.radiusSpinBoxValueChanged)

        self.frameNoSpinBox.valueChanged.connect(self.frameNoSpinBoxValueChanged)
        self.groupBox_2.hide()
        

        self.inputGraphicsView.viewport().setCursor(QtCore.Qt.ArrowCursor)
        #
        self.optionViewButton.pressed.connect(self.optionViewButtonPressed)
        self.zoomedGraphicsView.hide()

        self.dataFrameWidget.dataFrameChanged.connect(self.dataFrameChanged)
        self.dataFrameWidget.hide()
        self.handInputSystem.setColor(self.dataFrameWidget.getColor())
        
        #self.processDropedFile("/Users/ymnk/temp/Dast/2016/01/hoge.avi")
        #self.processDropedFile("./a.csv")        
    def dataFrameChanged(self,addedFrameFlag,editingNo,color):
        if addedFrameFlag:
            self.handInputSystem.addNewDataFrame()
        self.handInputSystem.setEditingNo(editingNo)
        self.handInputSystem.setColor(color)
        print(addedFrameFlag,color,editingNo)

    def optionViewButtonPressed(self):
        if self.groupBox_2.isVisible():
            self.optionViewButton.setText("<")
            self.groupBox_2.hide()
        else:
            self.optionViewButton.setText(">")
            self.groupBox_2.show()

    def overlayCheckBoxStateChanged(self, s):
        if self.overlayCheckBox.isChecked():
            self.frameBufferItemGroup.show()
        else:
            self.frameBufferItemGroup.hide()

        self.updateInputGraphicsView()

    def polyLineCheckBoxStateChanged(self, s):
        overlayFrameNo = self.frameNoSpinBox.value()

        min_value = max(self.currentFrameNo-overlayFrameNo,0)
        current_pos = self.currentFrameNo - min_value

        if self.handInputSystem is not None:
            self.handInputSystem.setDrawItem(current_pos, self.circleCheckBox.isChecked())
            self.handInputSystem.setDrawLine(self.lineCheckBox.isChecked())
            self.updateInputGraphicsView()

    def radiusSpinBoxValueChanged(self, value):
        if self.handInputSystem is not None:
            self.handInputSystem.setRadius(self.radiusSpinBox.value())
            self.updateInputGraphicsView()

    def frameNoSpinBoxValueChanged(self, value):
        if self.handInputSystem is not None:
            self.handInputSystem.setOverlayFrameNo(self.frameNoSpinBox.value())
            self.updateInputGraphicsView()
    def dragEnterEvent(self,event):
        event.acceptProposedAction()

    def dropEvent(self,event):
        # event.setDropAction(QtCore.Qt.MoveAction)
        mime = event.mimeData()
        if mime.hasUrls():
            urls = mime.urls()
            if len(urls) > 0:
                self.processDropedFile(urls[0].toLocalFile())

        event.acceptProposedAction()

    def processDropedFile(self,filePath):
        root,ext = os.path.splitext(filePath)
        if ext == ".filter":
#.........这里部分代码省略.........
开发者ID:UMATracker,项目名称:UMATracker-Commando,代码行数:103,代码来源:main.py

示例9: __init__

# 需要导入模块: from PyQt5.QtWidgets import QGraphicsScene [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsScene import sceneRect [as 别名]

#.........这里部分代码省略.........
        frontState.assignProperty(selectionItem, "visible", True)

        backState.assignProperty(pad, "fill", True)
        backState.assignProperty(backItem, "visible", True)
        backState.assignProperty(xRotation, "angle", 0.0)
        backState.assignProperty(yRotation, "angle", 0.0)
        backState.assignProperty(flipRotation, "angle", 180.0)
        backState.assignProperty(selectionItem, "visible", False)

        stateMachine.addDefaultAnimation(smoothXRotation)
        stateMachine.addDefaultAnimation(smoothYRotation)
        stateMachine.addDefaultAnimation(smoothXSelection)
        stateMachine.addDefaultAnimation(smoothYSelection)
        stateMachine.setInitialState(splashState)

        anyKeyTransition = QEventTransition(self, QEvent.KeyPress, splashState)
        anyKeyTransition.setTargetState(frontState)
        anyKeyTransition.addAnimation(smoothSplashMove)
        anyKeyTransition.addAnimation(smoothSplashOpacity)

        enterTransition = QKeyEventTransition(self, QEvent.KeyPress,
                Qt.Key_Enter, backState)
        returnTransition = QKeyEventTransition(self, QEvent.KeyPress,
                Qt.Key_Return, backState)
        backEnterTransition = QKeyEventTransition(self, QEvent.KeyPress,
                Qt.Key_Enter, frontState)
        backReturnTransition = QKeyEventTransition(self, QEvent.KeyPress,
                Qt.Key_Return, frontState)
        enterTransition.setTargetState(historyState)
        returnTransition.setTargetState(historyState)
        backEnterTransition.setTargetState(backState)
        backReturnTransition.setTargetState(backState)
        enterTransition.addAnimation(flipAnimation)
        returnTransition.addAnimation(flipAnimation)
        backEnterTransition.addAnimation(flipAnimation)
        backReturnTransition.addAnimation(flipAnimation)

        columns = size.width()
        rows = size.height()
        stateGrid = []
        for y in range(rows):
            stateGrid.append([QState(frontState) for _ in range(columns)])

        frontState.setInitialState(stateGrid[0][0])
        selectionItem.setPos(pad.iconAt(0, 0).pos())

        for y in range(rows):
            for x in range(columns):
                state = stateGrid[y][x]

                rightTransition = QKeyEventTransition(self, QEvent.KeyPress,
                        Qt.Key_Right, state)
                leftTransition = QKeyEventTransition(self, QEvent.KeyPress,
                        Qt.Key_Left, state)
                downTransition = QKeyEventTransition(self, QEvent.KeyPress,
                        Qt.Key_Down, state)
                upTransition = QKeyEventTransition(self, QEvent.KeyPress,
                        Qt.Key_Up, state)

                rightTransition.setTargetState(stateGrid[y][(x + 1) % columns])
                leftTransition.setTargetState(stateGrid[y][((x - 1) + columns) % columns])
                downTransition.setTargetState(stateGrid[(y + 1) % rows][x])
                upTransition.setTargetState(stateGrid[((y - 1) + rows) % rows][x])

                icon = pad.iconAt(x, y)
                state.assignProperty(xRotation, "angle", -icon.x() / 6.0)
                state.assignProperty(yRotation, "angle", icon.y() / 6.0)
                state.assignProperty(selectionItem, "x", icon.x())
                state.assignProperty(selectionItem, "y", icon.y())
                frontState.assignProperty(icon, "visible", True)
                backState.assignProperty(icon, "visible", False)

                setIconVisibleAnimation = QPropertyAnimation(icon, b'visible')
                setIconVisibleAnimation.setDuration(0)
                setVariablesSequence.addAnimation(setIconVisibleAnimation)

        scene = QGraphicsScene(self)
        scene.setBackgroundBrush(QBrush(QPixmap(":/images/blue_angle_swirl.jpg")))
        scene.setItemIndexMethod(QGraphicsScene.NoIndex)
        scene.addItem(pad)
        scene.setSceneRect(scene.itemsBoundingRect())
        self.setScene(scene)

        sbr = splash.boundingRect()
        splash.setPos(-sbr.width() / 2, scene.sceneRect().top() - 2)
        frontState.assignProperty(splash, "y", splash.y() - 100.0)
        scene.addItem(splash)

        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setMinimumSize(50, 50)
        self.setViewportUpdateMode(QGraphicsView.FullViewportUpdate)
        self.setCacheMode(QGraphicsView.CacheBackground)
        self.setRenderHints(QPainter.Antialiasing |
                QPainter.SmoothPixmapTransform | QPainter.TextAntialiasing)

        if QGLFormat.hasOpenGL():
            self.setViewport(QGLWidget(QGLFormat(QGL.SampleBuffers)))

        stateMachine.start()
开发者ID:Axel-Erfurt,项目名称:pyqt5,代码行数:104,代码来源:padnavigator.py

示例10: PianoKeys

# 需要导入模块: from PyQt5.QtWidgets import QGraphicsScene [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsScene import sceneRect [as 别名]
class PianoKeys(QGraphicsView):
    def __init__(self, parent):
        super().__init__(parent)

        self.setFocusPolicy(Qt.NoFocus)

        self.setBackgroundRole(QPalette.Window)
        self.setFrameShape(QFrame.NoFrame)
        self.setBackgroundBrush(QBrush(Qt.NoBrush))

        self._scene = QGraphicsScene(self)
        self.setScene(self._scene)

        self._keys = {}
        self._midi_to_key = {}
        for octave in range(2, 7):
            for idx, note in enumerate(['C', 'D', 'E', 'F', 'G', 'A', 'B']):
                pitch_name = '%s%d' % (note, octave)
                key = PianoKey(
                    parent,
                    140 * octave + 20 * idx,
                    pitch_name,
                    PianoKey.WHITE)
                self._keys[pitch_name] = key
                self._midi_to_key[music.NOTE_TO_MIDI[pitch_name]] = key
                self._scene.addItem(key)

            for idx, note in enumerate(['C#', 'D#', '', 'F#', 'G#', 'A#', '']):
                if not note:
                    continue
                pitch_name = '%s%d' % (note, octave)
                key = PianoKey(
                    parent,
                    140 * octave + 20 * idx + 10,
                    pitch_name,
                    PianoKey.BLACK)
                self._keys[pitch_name] = key
                self._midi_to_key[music.NOTE_TO_MIDI[pitch_name]] = key
                self._scene.addItem(key)


        size = self._scene.sceneRect().size()
        size = QSize(int(math.ceil(size.width())) + 1,
                     int(math.ceil(size.height())) + 10)
        self.setMinimumSize(size)
        self.setMaximumSize(size)

    _key2note = {
        0x5e: 'G2',   # <
        0x26: 'G#2',  # a
        0x34: 'A2',   # y
        0x27: 'A#2',  # s
        0x35: 'B2',   # x

        0x36: 'C3',   # c
        0x29: 'C#3',  #
        0x37: 'D3',   # v
        0x2a: 'D#3',  #
        0x38: 'E3',   # b
        0x39: 'F3',   # n
        0x2c: 'F#3',  # j
        0x3a: 'G3',   # m
        0x2d: 'G#3',  # k
        0x3b: 'A3',   # ,
        0x2e: 'A#3',  # l
        0x3c: 'B3',   # .

        0x3d: 'C4',   # -
        0x30: 'C#4',  # ä

        0x0a: 'F#4',  # 1
        0x18: 'G4',   # q
        0x0b: 'G#4',  # 2
        0x19: 'A4',   # w
        0x0c: 'A#4',  # 3
        0x1a: 'B4',   # e

        0x1b: 'C5',   # r
        0x0e: 'C#5',  # 5
        0x1c: 'D5',   # t
        0x0f: 'D#5',  # 6
        0x1d: 'E5',   # z
        0x1e: 'F5',   # u
        0x11: 'F#5',  # 8
        0x1f: 'G5',   # i
        0x12: 'G#5',  # 9
        0x20: 'A5',   # o
        0x13: 'A#5',  # 0
        0x21: 'B5',   # p

        0x22: 'C6',   # ü
        0x15: 'C#6',  # ^
        0x23: 'D6',   # ¨
    }

    def keyPressEvent(self, event):
        if event.isAutoRepeat():
            super().keyPressEvent(event)
            return

#.........这里部分代码省略.........
开发者ID:odahoda,项目名称:noisicaa,代码行数:103,代码来源:piano.py

示例11: BackgroundGeneratorDialog

# 需要导入模块: from PyQt5.QtWidgets import QGraphicsScene [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsScene import sceneRect [as 别名]
class BackgroundGeneratorDialog(Ui_BackgroundGeneratorDialog, QDialog):
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        Ui_BackgroundGeneratorDialog.__init__(self)
        self.setupUi(self)

        self.videoPlaybackInit()
        self.imgInit()

        self.generateButton.pressed.connect(self.generateBackground)


    def closeEvent(self,event):
        pass

    def videoPlaybackInit(self):
        self.videoPlaybackWidget.frameChanged.connect(self.setFrame, type=Qt.QueuedConnection)

    def setFrame(self, frame):
        if frame is not None:

            self.cv_img = frame
            self.updateInputGraphicsView()

            if self.fgbg is not None:
                self.updateOutputGraphicsView()

    def imgInit(self):
        self.inputScene = QGraphicsScene()
        self.inputGraphicsView.setScene(self.inputScene)
        self.inputGraphicsView.resizeEvent = self.inputGraphicsViewResized

        self.outputScene = QGraphicsScene()
        self.outputGraphicsView.setScene(self.outputScene)
        self.outputGraphicsView.resizeEvent = self.outputGraphicsViewResized

        self.fgbg = None

    def openVideoFile(self, filePath = None):
        if len(filePath) is not 0:
            self.filePath = filePath

            ret = self.videoPlaybackWidget.openVideo(filePath)
            if ret == False:
                return False

            self.videoPlaybackWidget.show()
            self.filterClassHash = None

            return True

    def updateInputGraphicsView(self):
        self.inputScene.clear()
        # self.inputScene.removeItem(self.inputPixMapItem)
        qimg = cvMatToQImage(self.cv_img)
        self.inputPixMap = QPixmap.fromImage(qimg)

        rect = QtCore.QRectF(self.inputPixMap.rect())
        self.inputScene.setSceneRect(rect)
        self.outputScene.setSceneRect(rect)

        self.inputPixMapItem = QGraphicsPixmapItem(self.inputPixMap)
        # self.inputScene.setBackgroundBrush(QBrush(self.inputPixMap))
        self.inputScene.addItem(self.inputPixMapItem)

        self.inputGraphicsView.viewport().update()
        self.inputGraphicsViewResized()

    def updateOutputGraphicsView(self):
        if False:
            out_img = self.fgbg.apply(self.cv_img, learningRate=0)
        else:
            bg = self.fgbg.getBackgroundImage()
            out_img = cv2.absdiff(self.cv_img, bg)

        self.outputScene.clear()
        qimg = cvMatToQImage(out_img)
        self.outputPixMap = QPixmap.fromImage(qimg)

        rect = QtCore.QRectF(self.outputPixMap.rect())
        self.outputScene.setSceneRect(rect)

        self.outputPixMapItem = QGraphicsPixmapItem(self.outputPixMap)
        self.outputScene.addItem(self.outputPixMapItem)

        self.outputGraphicsView.viewport().update()
        self.outputGraphicsViewResized()

    def inputGraphicsViewResized(self, event=None):
        self.inputGraphicsView.fitInView(self.inputScene.sceneRect(), QtCore.Qt.KeepAspectRatio)

    def outputGraphicsViewResized(self, event=None):
        self.outputGraphicsView.fitInView(self.outputScene.sceneRect(), QtCore.Qt.KeepAspectRatio)

    def generateBackground(self):
        minFrame = self.videoPlaybackWidget.getMinRange()
        maxFrame = self.videoPlaybackWidget.getMaxRange()
        stride = self.strideSpinBox.value()
        numFrames = int((maxFrame-minFrame)/stride)
        progress = QProgressDialog("Generating background...", "Abort", 0, numFrames, self)
#.........这里部分代码省略.........
开发者ID:ymnk13,项目名称:UMATracker,代码行数:103,代码来源:background_generator_dialog.py

示例12: Shufti

# 需要导入模块: from PyQt5.QtWidgets import QGraphicsScene [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsScene import sceneRect [as 别名]

#.........这里部分代码省略.........
        self.db.open()
        self.query.exec_("create table shuftery(filename text primary key, "
        "zoom real, winposx int, winposy int, winsizex int, winsizey int, "
        "hscroll int, vscroll int, rotate int)")
        return True
        
    def zoomIn(self):
        
        self.zoom *= 1.05
        self.updateView()
        
    def zoomOut(self):
        
        self.zoom /= 1.05
        self.updateView()
        
    def zoomReset(self):
        
        self.zoom = 1
        self.updateView()
        
    def rotateImg(self, clock):
        
        self.rotval += clock
        if self.rotval == 4:
            self.rotval = 0
        elif self.rotval < 0:
            self.rotval = 3
        self.rotate = self.rotvals[self.rotval]
        self.updateView()
        
    def fitView(self):
        
        self.view.fitInView(self.scene.sceneRect(), QtCore.Qt.KeepAspectRatio)
        if self.rotate == 0:
            self.zoom = self.view.transform().m11()
        elif self.rotate == -90:
            self.zoom = (self.view.transform().m12()) * -1
        elif self.rotate == -180:
            self.zoom = (self.view.transform().m11()) * -1
        else:
            self.zoom = self.view.transform().m12()
        
    def updateView(self):
        
        self.view.setTransform(QTransform().scale(self.zoom, self.zoom).rotate(self.rotate))
        
    def winState(self):
        
        self.winsizex = self.geometry().width()
        self.winsizey = self.geometry().height()
        self.vscroll = self.view.verticalScrollBar().value()
        self.hscroll = self.view.horizontalScrollBar().value()
        self.winposx = self.pos().x()
        self.winposy = self.pos().y()
        
    def dbInsert(self):
        
        self.query.exec_("insert into shuftery values('%s" % self.dbkey + 
        "', " + str(self.zoom) + ", " + str(self.winposx) + ", " + str(self.winposy) + 
        ", " + str(self.winsizex) + ", " + str(self.winsizey) + ", " + str(self.hscroll) + 
        ", " + str(self.vscroll) + ", " + str(self.rotate) + ")")
        
    def dbUpdate(self):
        
        self.query.exec_("update shuftery set zoom=" + str(self.zoom) + 
开发者ID:lmann03,项目名称:roadside-viewer,代码行数:70,代码来源:shufti.py

示例13: DocumentWindow

# 需要导入模块: from PyQt5.QtWidgets import QGraphicsScene [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsScene import sceneRect [as 别名]
class DocumentWindow(QMainWindow, ui_mainwindow.Ui_MainWindow):
    """DocumentWindow subclasses QMainWindow and Ui_MainWindow. It performs
    some initialization operations that must be done in code rather than
    using Qt Creator.

    Attributes:
        controller (DocumentController):
    """
    def __init__(self, parent=None, doc_ctrlr=None):
        super(DocumentWindow, self).__init__(parent)
        self.controller = doc_ctrlr
        doc = doc_ctrlr.document()
        self.setupUi(self)
        self.settings = QSettings()
        self._readSettings()
        # self.setCentralWidget(self.slice_graphics_view)
        # Appearance pref
        if not app().prefs.show_icon_labels:
            self.main_toolbar.setToolButtonStyle(Qt.ToolButtonIconOnly)

        # Outliner & PropertyEditor setup
        self.outliner_widget.configure(window=self, document=doc)
        self.property_widget.configure(window=self, document=doc)
        self.property_buttonbox.setVisible(False)

        self.tool_managers = None  # initialize

        # Slice setup
        self.slicescene = QGraphicsScene(parent=self.slice_graphics_view)
        self.sliceroot = SliceRootItem(rect=self.slicescene.sceneRect(),
                                       parent=None,
                                       window=self,
                                       document=doc)
        self.sliceroot.setFlag(QGraphicsItem.ItemHasNoContents)
        self.slicescene.addItem(self.sliceroot)
        self.slicescene.setItemIndexMethod(QGraphicsScene.NoIndex)
        assert self.sliceroot.scene() == self.slicescene
        self.slice_graphics_view.setScene(self.slicescene)
        self.slice_graphics_view.scene_root_item = self.sliceroot
        self.slice_graphics_view.setName("SliceView")
        self.slice_tool_manager = SliceToolManager(self, self.sliceroot)
        # Path setup
        self.pathscene = QGraphicsScene(parent=self.path_graphics_view)
        self.pathroot = PathRootItem(rect=self.pathscene.sceneRect(),
                                     parent=None,
                                     window=self,
                                     document=doc)
        self.pathroot.setFlag(QGraphicsItem.ItemHasNoContents)
        self.pathscene.addItem(self.pathroot)
        self.pathscene.setItemIndexMethod(QGraphicsScene.NoIndex)
        assert self.pathroot.scene() == self.pathscene
        self.path_graphics_view.setScene(self.pathscene)
        self.path_graphics_view.scene_root_item = self.pathroot
        self.path_graphics_view.setScaleFitFactor(0.9)
        self.path_graphics_view.setName("PathView")

        # Path toolbar
        self.path_color_panel = ColorPanel()
        self.path_graphics_view.toolbar = self.path_color_panel  # HACK for customqgraphicsview
        self.pathscene.addItem(self.path_color_panel)
        self.path_tool_manager = PathToolManager(self, self.pathroot)
        self.slice_tool_manager.path_tool_manager = self.path_tool_manager
        self.path_tool_manager.slice_tool_manager = self.slice_tool_manager
        self.tool_managers = (self.path_tool_manager, self.slice_tool_manager)

        self.insertToolBarBreak(self.main_toolbar)

        self.path_graphics_view.setupGL()
        self.slice_graphics_view.setupGL()

        # Edit menu setup
        self.actionUndo = doc_ctrlr.undoStack().createUndoAction(self)
        self.actionRedo = doc_ctrlr.undoStack().createRedoAction(self)
        self.actionUndo.setText(QApplication.translate("MainWindow", "Undo", None))
        self.actionUndo.setShortcut(QApplication.translate("MainWindow", "Ctrl+Z", None))
        self.actionRedo.setText(QApplication.translate("MainWindow", "Redo", None))
        self.actionRedo.setShortcut(QApplication.translate("MainWindow", "Ctrl+Shift+Z", None))
        self.sep = QAction(self)
        self.sep.setSeparator(True)
        self.menu_edit.insertAction(self.sep, self.actionRedo)
        self.menu_edit.insertAction(self.actionRedo, self.actionUndo)
        self.main_splitter.setSizes([400, 400, 180])  # balance main_splitter size
        self.statusBar().showMessage("")

        doc.setViewNames(['slice', 'path'])
    # end def

    def document(self):
        return self.controller.document()
    # end def

    def destroyWin(self):
        for mgr in self.tool_managers:
            mgr.destroy()
        self.controller = None
    # end def

    ### ACCESSORS ###
    def undoStack(self):
        return self.controller.undoStack()
#.........这里部分代码省略.........
开发者ID:hadim,项目名称:cadnano2.5,代码行数:103,代码来源:documentwindow.py

示例14: MainWindow

# 需要导入模块: from PyQt5.QtWidgets import QGraphicsScene [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsScene import sceneRect [as 别名]
class MainWindow(QMainWindow):



    def __init__(self):
        super(MainWindow, self).__init__()
        # read .ui file from QtDesigner
        __location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
        f = open(os.path.join(__location__, 'ui_window.ui'));
        uic.loadUi(f, self)
        self.doc = None
        self.setupUI()

    def setupUI(self):
        # actions
        root = QFileInfo(__file__).absolutePath()
        # self.actionUndo = QAction(QIcon(root+'/images/Undo-icon.png'),"undo",self)
        # self.actionMerge_domain = QAction(self)
        # self.actionCreate_toehold = QAction(self)
        # self.actionResize_toehold = QAction(self)
        # self.actionRemove_toehold = QAction(self)

        # connect menuBar, toolBar, dockWidget to self(mainWindow)
        self.dockWidget = DockWidget(self)
        self.menuBar = MenuBar(self)
        self.toolBar = ToolBar(self)
        self.addDockWidget(QtCore.Qt.RightDockWidgetArea,self.dockWidget)


        # main window setup
        root = QFileInfo(__file__).absolutePath()
        self.setWindowTitle('OtraCAD')
        self.setWindowIcon((QIcon(root+'/images/bug.png')))
        # splitter allows user control the size of child widgets by dragging the boundary between the children
        self.main_splitter = QtWidgets.QSplitter(self.centralwidget)
        self.path_splitter = QtWidgets.QSplitter(self.main_splitter)
        # renderView is where .json file is rendered in the window;
        # CustomQGraphicsView extends QGraphicsView, allow zooming in/out and drag by using "command+click"
        self.renderView = CustomQGraphicsView(self.path_splitter)




        # size polices
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.renderView.sizePolicy().hasHeightForWidth())
        self.renderView.setSizePolicy(sizePolicy)
        self.renderView.setMinimumSize(QtCore.QSize(0, 0))
        self.renderView.setMouseTracking(True)
        self.renderView.setFocusPolicy(QtCore.Qt.WheelFocus)
        self.renderView.setFrameShadow(QtWidgets.QFrame.Plain)
        self.renderView.setLineWidth(0)
        self.renderView.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.renderView.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.renderView.setRenderHints(QtGui.QPainter.Antialiasing|QtGui.QPainter.HighQualityAntialiasing|QtGui.QPainter.TextAntialiasing)
        self.renderView.setTransformationAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse)
        self.renderView.setObjectName("renderView")
        self.renderView.setupGL(self)
        self.gridLayout.addWidget(self.main_splitter, 0, 0, 1, 1)



    def updateRenderView(self,doc_ctrl):
        # set up render view to render imported .json file
         self.pathscene = QGraphicsScene(parent=self.renderView)
         self.pathroot = PathRootItem(rect=self.pathscene.sceneRect(),\
                                     parent=None,\
                                     window=self,\
                                     document= doc_ctrl._document)
         self.pathroot.setFlag(QGraphicsItem.ItemHasNoContents)
         self.pathscene.addItem(self.pathroot)
         self.pathscene.setItemIndexMethod(QGraphicsScene.NoIndex)
         assert self.pathroot.scene() == self.pathscene
         self.renderView.setScene(self.pathscene)
         self.renderView.scene_root_item = self.pathroot
         self.renderView._scale_fit_factor = 0.9
         self.renderView._name = 'renderView'
    #end def

    def setDoc(self,doc):
        # set documents for all child widgets
        self.doc = doc
        self.dockWidget.doc = doc
        self.toolBar.doc = doc
开发者ID:amylittleyang,项目名称:OtraCAD,代码行数:88,代码来源:mainWindow.py

示例15: Ui_MainWindow

# 需要导入模块: from PyQt5.QtWidgets import QGraphicsScene [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsScene import sceneRect [as 别名]

#.........这里部分代码省略.........
            frame = self.blocklyWebView.page().mainFrame()
            frame.evaluateJavaScript("Apps.setBlockData('{0}');".format(blockXML))

    def saveFilterFile(self):
        self.blocklyEvaluationTimer.stop()
        if self.filePath is not None:
            candidateFilePath = os.path.splitext(self.filePath)[0] + '.filter'
        else:
            candidateFilePath = userDir
        filePath, _ = QFileDialog.getSaveFileName(None, 'Save Filter File', candidateFilePath, "Filter files (*.filter)")

        if len(filePath) is not 0:
            logger.debug("Saving Filter file: {0}".format(filePath))

            frame = self.blocklyWebView.page().mainFrame()

            filterIO = FilterIO()
            filterIO.setBlockXMLData(frame.evaluateJavaScript("Apps.getBlockData();"))

            filterClassText = self.parseToClass(frame.evaluateJavaScript("Apps.getCodeFromWorkspace();"))
            filterIO.setFilterCode(filterClassText)

            filterIO.setBackgroundImg(self.fgbg)

            filterIO.save(filePath)

        self.blocklyEvaluationTimer.start()

    def inputGraphicsViewResized(self, event=None):
        self.inputGraphicsView.fitInView(QtCore.QRectF(self.inputPixmap.rect()), QtCore.Qt.KeepAspectRatio)

    def outputGraphicsViewResized(self, event=None):
        if self.outputPixmap is None:
            self.outputGraphicsView.fitInView(self.outputScene.sceneRect(), QtCore.Qt.KeepAspectRatio)
        else:
            self.outputGraphicsView.fitInView(QtCore.QRectF(self.outputPixmap.rect()), QtCore.Qt.KeepAspectRatio)

    def parseToClass(self, text):
        additionalText = """#self.fgbg = None
#self.resize_flag = {resize_flag}
#if self.resize_flag:
#    im_input = cv2.pyrDown(im_input)
if self.resize_flag:
    {input} = cv2.pyrDown({input})
if self.fgbg is not None:
    {input} = cv2.absdiff({input}, self.fgbg)
""".format(resize_flag=self.actionResize.isChecked(), input="{input}")
        text = additionalText + text

        lines = text.split("\n")
        classMemberPattern = r"^#"

        classMembers = []
        filterOperations = []

        for line in lines:
            if re.match(classMemberPattern, line):
                classMembers.append(line.lstrip("#"))
            else:
                filterOperations.append(line)

        generator = ClassTextGenerator('filterOperation')
        generator.functions['__init__']['lines'] = classMembers
        generator.functions['__init__']['args'] = ['im_input']

        filterOperations.append('return {output}')
开发者ID:ymnk13,项目名称:UMATracker,代码行数:70,代码来源:main.py


注:本文中的PyQt5.QtWidgets.QGraphicsScene.sceneRect方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。